1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
/**
* easyPoi框架导出excel 使用模板
*/
@SneakyThrows
private void easyPoiExportExcelWithTemplate(HttpServletResponse response) {
// 构建map
Map<Integer, Map<String, Object>> map = new HashMap<>();
HashMap<String, Object> sheet1 = new HashMap<>();
sheet1.put("key1", "value1");
sheet1.put("key2", "value2");
map.put(0, sheet1);
HashMap<String, Object> sheet2 = new HashMap<>();
sheet2.put("key1", "value1");
sheet2.put("key2", "value2");
map.put(1, sheet2);
// 创建临时文件,将模板文件内容复制到临时文件
Path tempPath;
try (FileInputStream fis = new FileInputStream(this.getClass().getResource("/").getPath() + "换电站运营周报表模板.xlsx")) {
File tempFile = File.createTempFile("temp", ".xlsx");
tempPath = tempFile.toPath();
Files.copy(fis, tempPath, StandardCopyOption.REPLACE_EXISTING);
}
// 对临时文件写值,再写到ServletOutputStream
TemplateExportParams templateExportParams = new TemplateExportParams(tempPath.toString(), map.keySet().toArray(new Integer[]{}));
Workbook sheets = ExcelExportUtil.exportExcel(map, templateExportParams);
sheets.write(response.getOutputStream());
sheets.close();
// 构建response
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("fileName", StandardCharsets.UTF_8)
.replaceAll("\\+", "%20")
.replaceAll("%2F", "/")
+ ".xlsx");
response.setContentType("application/vnd.ms-excel"); // application/json application/pdf
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
}
|