包引用的 cn.hutool.poi.excel下面的 public void exportResult(List<PocErpRelationVO> records,boolean isPoc, HttpServletResponse response){ if(CollectionUtils.isEmpty(records)){ throw new BusinessException("导出数据为空"); } log.info("读取数据完毕"); cn.hutool.poi.excel.ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true); addExportHeaderAliasMethod(writer); writer.merge(16, "售点绑定列表"); // 指定字符集 response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 指定下载名字拼接,主要是前台传进来的数据 ServletOutputStream out = null; try { response.setHeader("Content-Disposition", "attachment;filename=售点绑定列表.xlsx"); out = response.getOutputStream(); writer.flush(out, true); } catch (IOException e) { log.info("异常", e); } finally { // 关闭writer writer.close(); // 关闭输出Servlet流 IoUtil.close(out); } }
private void addExportHeaderAliasMethod(cn.hutool.poi.excel.ExcelWriter writer) { writer.addHeaderAlias("pocId", "客户ID"); //todo 添加对象的code,列名称 }
导入
public static final String[] ERP_RELATION_EXCEL_HEAD = {"经销商ID","xxxx"}; public static final String[] ERP_RELATION_EXCEL_HEAD_ALIAS= {"erpCustomerId","xxxx"}; 步骤1.解析file对象到list集合 List<Map<String, Object>> result = Assert.requireNonNull(ExcelUtils.importExcel(file, ErpConstants.ERP_RELATION_EXCEL_HEAD, ErpConstants.ERP_RELATION_EXCEL_HEAD_ALIAS), ApiCode.DATA_NOT_FOUND);
public static List<Map<String, Object>> importExcel(MultipartFile file, String[] head, String[] headerAlias) { try { return ExcelUtils.importExcel(file.getInputStream(), head, headerAlias); } catch (IOException e) { log.error("Excel数据转list异常:{}", e.getMessage()); return Collections.emptyList(); } }
/** * 读取excel表格内容返回List<Map> * * @param inputStream excel文件流 * @param head 表头数组 * @param headerAlias 表头别名数组 */ public static List<Map<String, Object>> importExcel(InputStream inputStream, String[] head, String[] headerAlias) { ExcelReader reader = ExcelUtil.getReader(inputStream); List<Object> header = reader.readRow(0); //替换表头关键字 if (ArrayUtils.isEmpty(head) || ArrayUtils.isEmpty(headerAlias) || head.length != headerAlias.length || CollectionUtils.isEmpty(header)) { return Collections.emptyList(); } else { for (int i = 0; i < head.length; i++) { if (head[i].equals(header.get(i))) { reader.addHeaderAlias(head[i], headerAlias[i]); } else { log.error("模板表头:{} 读取的表头:{}", head[i], header.get(i)); throw new BusinessException("模板不匹配,请下载最新模板"); } } } //读取指点行开始的表数据(以下介绍的三个参数也可以使用动态传入,根据个人业务情况修改) //1:表头所在行数 2:数据开始读取位置 Integer.MAX_VALUE:数据读取结束行位置 return reader.read(0, 1, Integer.MAX_VALUE); }