最开始是要研究java+ftl模板的方式导出excel,研究了两天发现问题太多了。网上也找了很多案例,基本都不能成功导出excel。转而研究通过excel模板导出excel,发现比制作ftl模板要简单的多,代码量也比用ftl模板少很多。话不多说,上代码。
一、excel模板制作
1.将excel中需要赋值的单元格,设置占位符

2.将文件另存为.xlsx或xls格式的文件
二、引用jxl依赖
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0.3</version>
</dependency>
三、
@RequestMapping("/export")
private void exportExcel( HttpServletRequest request,HttpServletResponse response) throws Exception {
//获取待导出的数据
Map<String,object> dataMap=new HashMap<>();
List<Bo> list=new ArrayList<>();
dataMap.put("dataList",list);
//获得模版(获取模板地址,)
String tempFileName = request.getSession().getServletContext().getRealPath("/excelTemplate");
tempFileName=tempFileName+"模板.xlsx"
//导出列表名
String fileName = currntTime+"列表.xlsx";
//文件名称统一编码格式
fileName = URLEncoder.encode(fileName, "utf-8");
//生成的导出文件
File exportFile = File.createTempFile(fileName, ".xlsx");
//transformer转到Excel
XLSTransformer transformer = new XLSTransformer();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//将数据添加到模版中生成新的文件
transformer.transformXLS(tempFileName, dataMap, exportFile.getAbsolutePath());
//将文件输入
InputStream inputStream = new FileInputStream(exportFile);
// 设置response参数,可以打开下载页面
response.reset();
//设置响应文本格式
//response.setContentType("application/vnd.ms-excel;charset=utf-8");//xls
esponse.setContentType(“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”);//xlsx
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
//将文件输出到页面
ServletOutputStream out = response.getOutputStream();
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// 根据读取并写入
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (ParsePropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//使用完成后关闭流
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (IOException e) {
}
}
}