SpringBoot實現導出Excel功能(數據使用Mybatis-Plus分頁插件)


直接上代碼

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()參數

 

 

 問題解決了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM