SpringBoot實現匯出Excel功能(資料使用Mybatis-Plus分頁外掛)
阿新 • • 發佈:2020-10-13
直接上程式碼
Controller層
@Slf4j @RestController @RequestMapping("/thermal/tatsworksheettargetd") public class TaTsWorksheetTargetDController { @Autowired private TaTsWorksheetTargetDService taTsWorksheetTargetDService; @GetMapping("/exportTargetD") public R exportTargetD(@RequestParam(value = "prvnceId",required = false)String prvnceId, @RequestParam(value = "pageSize",defaultValue = "20")String pageSize, @RequestParam(value = "pageNum",defaultValue = "1")String pageNum, @RequestParam(value = "tsType",required = false)String tsType, @RequestParam(value= "monthId",required = false)String monthId, HttpServletResponse response) { try { taTsWorksheetTargetDService.exportTargetD(prvnceId,tsType,monthId,response); return R.ok(); } catch (Exception e) { log.error(e.getMessage(), e);return R.error("匯出Excel出現錯誤!"); } }
}
Service層
void exportTargetD(String prvnceId, String tsType, String monthId, HttpServletResponse response);
ServiceImpl層
@Override public void exportTargetD(String prvnceId,String tsType,String monthId,HttpServletResponse response) { try { ExcelWriter writer = new ExcelWriter(true,"投訴資訊表"); String fileName; //設定檔名稱 fileName = "投訴資訊.xlsx"; //建立標題對映 exportTitleMap(writer); //未對映的不顯示 writer.setOnlyAlias(true); //設定分頁條件 //獲取資料 IPage<Map> excelList = taTsWorksheetTargetDDao.getMapData(new Page(1,99999),monthId,prvnceId,tsType); writer.write(excelList.getRecords()); writer.autoSizeColumnAll(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "iso8859-1")); ServletOutputStream out = response.getOutputStream(); writer.flush(out, true); //關閉Writer,釋放記憶體 writer.close(); //此處記得關閉輸出Servlet流 IoUtil.close(out); } catch (Exception e) { log.error(e.getMessage(), e); } }
遇到的問題
首先,我們匯出Excel需要呼叫查詢介面獲取資料,問題出現了,我們在查詢介面的時候使用了Mybatis-Plus分頁外掛,所以我們需要拿Ipage<Map>來接收資料,但是當我們把excelList這個引數傳給writer.write中時,會發現報錯。
匯出Excel使用的是Hutool工具,分頁使用的是Mybatis-Plus分頁外掛,個人覺得是這兩種工具作者不同,不支援這樣的傳參。(小白一個如果有大神明白怎麼回事希望能不吝賜教 ^ ^)
解決方案
點選進入Page類
裡面的 List<T> records 就是我們實際分頁的資料,所以在剛才傳參的地方傳入excelList.getRecords()引數