easyExcel匯出多個list列表的excel

dyy0213發表於2020-12-03

使用easyExcel 的版本為2.2.6,在1個excel裡面匯出多個list

模板
在這裡插入圖片描述
匯出後excel

在這裡插入圖片描述

@ApiOperation("test")
    @GetMapping("test")
    public void test(HttpServletResponse response) {
        try{

            //準備第一個list
            List<UserAddVo> list1 = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                UserAddVo userAddVo = new UserAddVo();
                userAddVo.setAccount( i + "賬號");
                userAddVo.setMobile("1315267999" + i);
                list1.add(userAddVo);
            }

            //準備第二個list資料
            List<UserAddVo> list2 = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                UserAddVo userAddVo = new UserAddVo();
                userAddVo.setPositionName( i + "職位");
                userAddVo.setMobile("1315267999" + i);
                list2.add(userAddVo);
            }


            //讀取模板輸入流
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("static/template/1.xlsx");

            //設定檔名稱
            String fileName = URLEncoder.encode("" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            //設定檔案型別
            response.setContentType("application/vnd.ms-excel");
            //設定編碼格式
            response.setCharacterEncoding("utf-8");
            // https://www.jb51.net/article/30565.htm Content-Disposition 使用說明
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //建立excel
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).build();
//           建立sheet
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

            // 如果有多個list 模板上必須有{字首.} 這裡的字首就是 a,然後多個list必須用 FillWrapper包裹
            excelWriter.fill(new FillWrapper("a", list1), fillConfig, writeSheet);
            excelWriter.fill(new FillWrapper("b", list2), fillConfig, writeSheet);

            Map map = new HashMap<>();
            map.put("total",111);


            excelWriter.fill(map, writeSheet);

            // 別忘記關閉流
            excelWriter.finish();


        }catch (Exception e){
            e.printStackTrace();
        }
    }

相關文章