EasyExcel 复杂表格导出
复杂表格导出思路导入依赖定义模板核心代码(填充模板)下载导出删除临时文件复杂表格导出思路
引入依赖构建表格模板定义填充模板数据填充模板下载文件注意wed前端分两次调用你 (先生成再下载)官方Excel地址导入依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel-core</artifactId><version>3.1.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel-support</artifactId><version>3.1.1</version></dependency>
定义模板
定义固定模板如图 (demo.xlsx
)模板中的占位符分两类{a}
与{.a}
其中{a}
(不带点)不可循环替换{.a}
(带点)可循环替换核心代码(填充模板)
public ShopExcel simpleFill() {Shop shop = new Shop();// 获取项目当前路径String path = System.getProperty("user.dir") + fileConfig;// 创建文件夹java.io.File pfile = new java.io.File(path);if (!pfile.exists()) {pfile.mkdirs();}// 判模板文件是否存在if (FilesUtils.fileExists(Paths.get(path, "demo.xlsx"))) {/*** 头部信息填充* 对应 签名人,送货人,收货人,备注,日期* {a}(占位符不带点的)*/shop = selectShopList(id);// 模板存放路径String templateFileName = path + "demo.xlsx";// 下载路径String fileName = path + "店铺清单统计.xlsx";/*** 详细信息填充* 对应 序号,商品编号 等* {.a}(占位符带点的)*/List<ShopInfo> shopInfos = shop.getShopInfoList();/**核心代码 填充过程* 模板中的占位符必须和对象中的属性、map中的键值名相同才可替换成功*/try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {WriteSheet writeSheet = EasyExcel.writerSheet().build();FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();// 循环LiSt填充模板excelWriter.fill(shopInfos, fillConfig, writeSheet);Map<String, Object> map = new HashMap<>();map.put("a", shop.a);map.put("b", shop.b);map.put("c", shop.c);map.put("time", shop.time);map.put("num", shop.num);map.put("one","");// 填充map模板excelWriter.fill(map, writeSheet);}}return null;}
下载导出
@GetMapping("downloadFile")@ApiOperation("导出商品单")@UserOperationLog(module = "导出商品单", operationDesc = "导出商品单")// url 对应 String fileName = path + "店铺清单统计.xlsx";public void downloadFileUrl(@RequestParam("url") String url, HttpServletResponse response) {try {FilesUtils.downloadFile(response, "." + url);} catch (Exception e) {log.error("下载失败", e);}}
删除临时文件
String path = System.getProperty("user.dir");// 判断文件是否存在if (FilesUtils.fileExists(Paths.get(path, url))) {File file = new File(path + url);file.delete();}// 判断文件是否存在public static boolean fileExists(Path filePath) {boolean ret = false;File testFile = new File(String.valueOf(filePath));if (testFile.exists()) {ret = true;}return ret;}