1,首先导入阿里的jar包
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.0.2</version> </dependency> |
2,将模板excel文件放在对应目录下,取文件时根据存放路径取
①模板内容
②模板存放位置
3,编写util类
public class TemplateExcelUtils{
/**
* 导出文件时为Writer生成OutputStream.
* @param fileName 文件名
* @param response response
* @return ""
*/
public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
return response.getOutputStream();
} catch (IOException e) {
throw new Exception("导出excel表格失败!", e);
}
}
}
4,编写测试代码
@RestController
@RequestMapping("/user")
public class ExcelTest {
@GetMapping("/downExcelTest")
public void downExcel2(HttpServletResponse response) {
InputStream is= null;
Map<String, Object> map = new HashMap<>();
map.put("nowDay", "2023-06-13");
map.put("customerName", "测试客户名");
map.put("customerNo", "测试客户编号");
map.put("solutiomTime", "2023-06-09");
map.put("amount", "2000");
map.put("userName", "张三");
map.put("taskNo", "202306130001");
map.put("taskNo", "1001");
map.put("processingTime", "2023-06-09");
map.put("longAmount", "500");
map.put("shortAmount", "300");
map.put("accountNo", "CN20230613");
// 取出模板
try {
is = ResourceUtil.getStream("templates/ErrorAccInfo.xlsx");
//定义最终导出的文件名称
String fileName = "测试文档.xlsx";
ExcelWriter excelWriter = EasyExcel.write(TemplateExcelUtils.getOutputStream(fileName, response)).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// 这个传进去的 map 就是非表格数据
excelWriter.fill(map, writeSheet);
excelWriter.finish();
} catch(Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5,测试。启动项目后舒服对应地址
6,测试结果
标签:map,excel,fileName,文档,put,response,模板 From: https://www.cnblogs.com/802syy/p/17476744.html