*Web中的EasyExcel匯出Excel(不建立物件且自定義合併單元格策略)
阿新 • • 發佈:2021-02-11
Web中的EasyExcel匯出Excel(不建立物件且自定義合併單元格策略)
適用於多張表(只查單表資料就用建立物件那種方法)
Controller
@RequestMapping(value = "/downloadPlanList", method = RequestMethod.GET) @ApiOperation(value = "下載") public void exportExcel(HttpServletResponse response) throws IOException { dyplanService.exportPlanList(response); }
Service
@Override public void exportPlanList(HttpServletResponse response) { List<List<Object>> planList= getPlanList(); try { response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=demo.xlsx"); //需要合併的列(不需要合併就忽略) int[] mergeColumeIndex = {0,1,2,5,6,7,8,9,10}; // 從哪一行開始合併 int mergeRowIndex = 0; // 建立excel EasyExcel.write(response.getOutputStream()) .head(excelHead()) // 自適應列寬(不需要就忽略) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 單元格合併策略(不需要就忽略) .registerWriteHandler(new LocalCellMergeStrategy(mergeRowIndex, mergeColumeIndex)) // 時間轉換 .registerConverter(new LocalDateTimeConverter()) .sheet("模板") .doWrite(planList); } catch (Exception e) { logger.error("下載報表異常:{}", e.getMessage()); throw new RuntimeException("下載報表異常"); } } /** * 組裝生成excel需要的欄位 * @param nodeId * @return */ public List<List<Object>> getPlanList(String nodeId){ List<Dyplan> dyplanList = dyplanMapper.getDyPlanList(nodeId); (中間根據具體業務組裝資料) .... return dataList; } /** * 組裝excel頭部 * @return */ private List<List<String>> excelHead() { List<List<String>> headList = new ArrayList(); headList.add(new ArrayList() {{ add("工作年度"); }}); // 下面這種寫法,可以實現複雜的頭 headList.add(new ArrayList() {{ add("工作內容"); add("資源型別"); }}); headList.add(new ArrayList() {{ add("工作內容"); add("數量"); }}); (具體業務具體處理) ...... return headList; }
上面實現的頭部效果:
自定義Converter(解決LocalDateTime日期轉換的問題)
注:EasyExcel支援Date型別,可以直接匯入匯出
public class LocalDateTimeConverter implements Converter<LocalDateTime> { @Override public Class supportJavaTypeKey() { return LocalDateTime.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception { return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } @Override public CellData convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception { return new CellData<>(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); } }
自定義合併單元格策略
參考:EasyExcel匯出自定義合併單元格策略.