采用jxl编写excel https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl
/**
* 下载Excel模板
*
* @throws Exception
*/
@RequestMapping("/flowDataStencilExc")
public void flowDataStencilExc(HttpServletRequest request, HttpServletResponse response) throws Exception {
// String templateName = request.getParameter("templateName");
// // 下载文件名
// String fileName = request.getParameter("fileName");
// 模板名称
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".xls";
// response.reset();
// response.setContentType("application/x-download;charset=UTF-8");
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
// response.setContentType("multipart/form-data");
// 2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
response.addHeader("Content-Type", "application/vnd.ms-excel");
OutputStream out = response.getOutputStream();
//创建一个Excel文件
try {
WritableWorkbook book = Workbook.createWorkbook(out);
//创建Excel中的页面,设置页面名称,页面号由0开始,页面会按页面号从小到大的顺序在Excel中从左向右排列
WritableSheet sheet1 = book.createSheet("Sheet_1", 0);
// //设置要合并单元格的下标
// sheet1.mergeCells(0, 0, 1, 1);
// //作用是指定第i+1行的高度,比如将第一行的高度设为200
// sheet1.setRowView(0, 1000);
//作用是指定第i+1列的宽度,比如将第一列的宽度设为30
sheet1.setColumnView(0, 30);
// WritableSheet sheet2 = book.createSheet("Sheet_2", 1);
//设置单元格的样式
WritableCellFormat cellFormat = new WritableCellFormat();
//设置水平居中
cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
//设置垂直居中
cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//设置自动换行
cellFormat.setWrap(true);
//设置显示的字体样式,字体,字号,是否粗体,字体颜色
cellFormat.setFont(new WritableFont(WritableFont.createFont("微软雅黑"), 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK));
//设置单元格背景色
// cellFormat.setBackground(jxl.format.Colour.BRIGHT_GREEN);
//创建一个单元格,并按行列坐标进行指定的内容写入 ,最后加入显示的样式 c 竖 r 横
Label labeltime = new Label(0, 0, "时间(整点)", cellFormat);
Label labelq = new Label(1, 0, "流量", cellFormat);
//将行列的值写入页面
sheet1.addCell(labeltime);
sheet1.addCell(labelq);
//设置单元格的样式
WritableCellFormat cellFormat2 = new WritableCellFormat();
//设置水平居中
cellFormat2.setAlignment(jxl.format.Alignment.CENTRE);
//设置垂直居中
cellFormat2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//创建数字类型的行列值
Number number = new Number(1, 1, 78.91, cellFormat2);
//创建日期类型数据,并添加
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String parse = simpleDateFormat.format(new Date());
String s = parse.substring(0,parse.length() - 2) + "00";
jxl.write.DateTime dateTime = new DateTime(0, 1, simpleDateFormat.parse(s),
new WritableCellFormat(new DateFormat("yyyy/m/d h:mm")));
// Label dateTime = new Label(0, 1, simpleDateFormat.format(new Date()), cellFormat2);
sheet1.addCell(dateTime);
//将数字类型的行列值插入指定的页面
sheet1.addCell(number);
//开始执行写入操作
book.write();
//关闭流
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}