Easypoi导出复杂excel文件
CodeSpike 人气:0之前做的excel文件导出都相对简单,用的都是公司自己封装的一些poi方法,导出内容都是表头+一行行的数据,但是这次需要导出的excel复杂度高了不少,自己用现有方法做比较麻烦,因此引入了Easypoi 进行实现。
之所以用Easypoi我是看中了它可以直接根据现有模板填充数据实现excel生成,而模板产品已经给出,那么接下来只需要稍微做修改就能使用,修改后的模板如图:
对照着官方文档的示例(http://easypoi.mydoc.io/ ) 很容易就能理解模板的使用规则
注意其中的{{$fe: 是遍历listmap变量循环填充数据行,其他则是类似占位符,很好理解
//代码就纯粹只是把模板的占位符和变量对应起来 Map<String, Object> map = new HashMap<String, Object>(); map.put("code", customer.getCode()); map.put("name", customer.getName()); map.put("mobile", customer.getMobile()); map.put("membershipGrade", customer.getMembershipGrade()); map.put("zzyMembershipGrade", customer.getZzyMembershipGrade()); map.put("addressComplete", customer.getAddressComplete()); List<Map<String, String>> listMap = new ArrayList<Map<String, String>>(); map.put("maplist", listMap); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (MainOrderSubOrderFinanceResult financeResult : mainOrderSubOrderFinanceResults) { Map<String, String> lm = new HashMap<String, String>(); lm.put("orderCode", financeResult.getOrderCode()); lm.put("payStatusDesc", financeResult.getPayStatusDesc()); lm.put("settlementTypeDesc", financeResult.getSettlementTypeDesc()); lm.put("billDate", dateFormat.format(financeResult.getBillDate())); lm.put("totalAmount", financeResult.getTotalAmount().stripTrailingZeros().toPlainString()); lm.put("discountAmount", financeResult.getDiscountAmount().stripTrailingZeros().toPlainString()); lm.put("amount", financeResult.getAmount().stripTrailingZeros().toPlainString()); lm.put("payAmount", financeResult.getPayAmount().stripTrailingZeros().toPlainString()); lm.put("amountPaid", financeResult.getAmountPaid().stripTrailingZeros().toPlainString()); listMap.add(lm); sumTotalAmount = sumTotalAmount.add(financeResult.getTotalAmount()); sumDiscountAmount = sumDiscountAmount.add(financeResult.getDiscountAmount()); sumAmount = sumAmount.add(financeResult.getAmount()); sumPayAmount = sumPayAmount.add(financeResult.getPayAmount()); sumAmountPaid = sumAmountPaid.add(financeResult.getAmountPaid()); } map.put("sumTotalAmount", sumTotalAmount); map.put("sumDiscountAmount", sumDiscountAmount); map.put("sumAmount", sumAmount); map.put("sumPayAmount", sumPayAmount); map.put("sumAmountPaid", sumAmountPaid); //生成临时模板文件 String url=""; try { File temp = File.createTempFile("exportCreditBillResult", ".xlsx"); FileUploadHelper.inputStream2File(this.getClass().getClassLoader().getResourceAsStream("exportCreditBillResult.xlsx"),temp); url=temp.getAbsolutePath(); temp.deleteOnExit(); } catch (IOException e) { } TemplateExportParams params = new TemplateExportParams(url); Workbook workbook = ExcelExportUtil.exportExcel(params, map);
做这个功能有一个关键点:
由于TemplateExportParams构造函数只支持传入文件路径,而直接传入resource下的模板文件路径在线上环境会有问题(本地没问题),因此需要用getResourceAsStream读取后生成临时文件,再把临时文件url传入
加载全部内容