jxls--按模板导出

来源:互联网 发布:淘宝耐克鞋正品 编辑:程序博客网 时间:2024/06/05 00:13
public void exportExcelOrder(HttpServletResponse response, String orderCode, String mobile) {ExportOrderDTO dto = service.findExportOrderDTOByOrderCode(orderCode, mobile);// 获取参数if (Objects.nonNull(dto)) {Map<String, ExportOrderDTO> beans = Maps.newHashMap();beans.put("entity", dto);XLSTransformer transformer = new XLSTransformer();InputStream in = null;OutputStream out = null;SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");String outputFileName = "OrderDetail_" + sdf.format(new Date()) + ".xlsx";response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");try {URL url = ExportController.class.getResource("/static/file/" + "order_template.xlsx");// 判断是否为解决方案订单if(Objects.equals(dto.getOrderType(), OrderType.SOLUATE)){url = ExportController.class.getResource("/static/file/" + "solute_order_template.xlsx");}File file = new File(url.getFile());in = new BufferedInputStream(new FileInputStream(file));Workbook workbook = transformer.transformXLS(in, beans);if(Objects.equals(dto.getOrderType(), OrderType.SOLUATE)){// 合并单元格Sheet sheetAt = workbook.getSheetAt(0);int lastRowNum = sheetAt.getLastRowNum();sheetAt.addMergedRegion(new CellRangeAddress(lastRowNum-2, lastRowNum-2, 1, 3));sheetAt.addMergedRegion(new CellRangeAddress(lastRowNum-2, lastRowNum-2, 5, 7));sheetAt.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 5, 7));}out = response.getOutputStream();workbook.write(out);out.flush();} catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}}

模板样例:




entity中的参数要与模板中的参数对应.


不知道什么原因,用第一个模板时,并不能完全按照模板导出,需要自己在controller中处理一下,猜测是因为foreach的原因.