java poi 動態多表頭導出數據


1、maven依賴

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

2、數據集合類

public class Demo1 {

    private int id;

    private String name;

    private int age;

    private List<Demo2> demo2; // List<?> 也可以

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<Demo2> getDemo2() {
        return demo2;
    }

    public void setDemo2(List<Demo2> demo2) {
        this.demo2 = demo2;
    }
}

3、表格樣式工具類

public class SheetStyle {
    
    /**
     * 水平居中、垂直居中
     * 字體:宋體
     * 字體大小:16號
     * 加粗
     * @param workbook
     * @return
     */
    public static CellStyle getStyle(XSSFWorkbook workbook) {
        CellStyle cellstyle=workbook.createCellStyle();
        cellstyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellstyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        Font font=workbook.createFont();//字體
        font.setFontName("宋體");//字體
        font.setFontHeightInPoints((short)18);//字號
        font.setBold(true);//加粗
        cellstyle.setFont(font);
        setBorderStyle(cellstyle);
        return cellstyle;
    }

    /**
     * 獲取默認的cell表格樣式,加邊框,水平居中,垂直居中
     * @param workbook
     * @return
     */
    public static CellStyle getTextCellStyle(XSSFWorkbook workbook) {
        CellStyle style=workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        setBorderStyle(style);
        return style;
    }
    /**
     * 獲取默認的cell表格樣式,加邊框,水平居中,垂直居中
     * @param workbook
     * @return
     */
    public static CellStyle getNumCellStyle(XSSFWorkbook workbook) {
        CellStyle style=workbook.createCellStyle();
        XSSFDataFormat df = new XSSFWorkbook().createDataFormat();
        style.setAlignment(HorizontalAlignment.RIGHT);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        style.setDataFormat(df.getFormat("0.00"));
        Font font=workbook.createFont();//字體
        font.setFontName("宋體");//字體
        font.setFontHeightInPoints((short)11);//字號
        style.setFont(font);
        setBorderStyle(style);
        return style;
    }

    /**
     * 邊框樣式
     * @param style
     */
    public static void setBorderStyle(CellStyle style) {
        style.setBorderBottom(BorderStyle.THIN); //下邊框
        style.setBorderLeft(BorderStyle.THIN);//左邊框
        style.setBorderTop(BorderStyle.THIN);//上邊框
        style.setBorderRight(BorderStyle.THIN);//右邊框
    }

    /**
     * 奇數行
     * 背景顏色為黃色
     * @param style
     */
    public static void setCellStyleYellow(CellStyle style) {
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    }
    /**
     * 偶數行
     * 背景顏色為LIME
     * @param style
     */
    public static void setCellStyleLime(CellStyle style) {
        style.setFillForegroundColor(IndexedColors.LIME.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    }
    /**
     * 字體設置紅色
     * @param workbook
     * @param style
     */
    public static void setFontRedColor(XSSFWorkbook workbook,CellStyle style) {
        Font font=workbook.createFont();//字體
        font.setColor(IndexedColors.RED.getIndex());
        style.setFont(font);
    }

4、表格生成工具類

public class ExcelExport {
    /**
     * 一對多模式子類行轉列導出數據(指定子類某一項作為子類一級標題) 子項為數值類型帶匯總
     * @param fatTitle 父類顯示列
     * @param sonTitle 子類一級標題
     * @param sonTitleTow 子類二級標題
     * @param dataList 數據行 數據格式 a,b,c,List<d>
     * @throws IOException
     */

    public static void outExcel(
            Map<String,Object> fatTitle,
            List<String> sonTitle,
            Map<String,Object> sonTitleTow,
            List<Map<String,Object>> dataList
    ) throws IOException {
        //創建工作薄對象
        XSSFWorkbook workbook = new XSSFWorkbook();//這里也可以設置sheet的Name
        //創建工作表對象
        XSSFSheet sheet = workbook.createSheet();
        //創建單元格空對象
        XSSFCell cell = null;
        //創建合並空對象
        CellRangeAddress region = null;
        //設置標題
        XSSFRow title = sheet.createRow(0);//設置第一行,從零開始
        //設置標題行高
        title.setHeightInPoints(40);
        //統計合並列(父類屬性+子類顯示屬性*子類標題)
        int titleColumn = fatTitle.size()+(sonTitle.size()+1)*sonTitleTow.size()-1;
        for (int i = 0; i <= titleColumn; i++) {
            cell = title.createCell(i);
            cell.setCellValue("測試數據標題");
            cell.setCellStyle(SheetStyle.getStyle(workbook));
        }
        //合並單元格
        region = new CellRangeAddress(0, 0, 0, titleColumn);
        sheet.addMergedRegion(region);
        sheet.setColumnWidth(0,3000);
        //先創建父類標題
        XSSFRow row = sheet.createRow(1);//設置第一行
        //設置第二行
        XSSFRow row1 = sheet.createRow(2);
        row.setHeightInPoints(20);//設置行高
        row1.setHeightInPoints(18);//設置行高
        int i = 0;  // 列數
        //循環添加父類標題
        for (String s : fatTitle.keySet()) {
            //繪制單元格
            cell=row.createCell(i);
            //添加數據
            cell.setCellValue(fatTitle.get(s).toString());
            //添加樣式
            cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
            //設置要合並的單元格樣式
            cell = row1.createCell(i);
            cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
            //合並 (4個參數,分別為起始行,結束行,起始列,結束列)
            region = new CellRangeAddress(1, 2, i, i++);
            sheet.addMergedRegion(region);
            sheet.setColumnWidth(i,3000);
        }
        //循環添加子類一級標題
        int i_1=i;  // 子類一級標題起始列
        for (String s : sonTitle){
            //繪制單元格
            cell=row.createCell(i_1);
            //添加數據
            cell.setCellValue(s);
            //添加樣式
            cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
            //設置要合並的單元格樣式
            cell = row.createCell(i_1+1);
            cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
            //合並單元格
            region = new CellRangeAddress(1, 1,i_1, i_1+sonTitleTow.size()-1);
            sheet.addMergedRegion(region);
            //循環添加子類二級表頭
            int i_2=i_1;  // 子類二級標題起始列
            for (String s1 : sonTitleTow.keySet()){
                cell = row1.createCell(i_2);
                cell.setCellValue(sonTitleTow.get(s1).toString());
                cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
                sheet.setColumnWidth(i_2,2500);
                i_2++;
            }
            i_1 = i_1+sonTitleTow.size();
        }
        //添加匯總標題
        int i_3 = i_1;
        for (String s1 : sonTitleTow.keySet()){
            cell = row.createCell(i_3);
            cell.setCellValue(sonTitleTow.get(s1).toString()+"匯總");
            cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
            //設置要合並的單元格樣式
            cell = row1.createCell(i_3);
            cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
            //合並單元格
            region = new CellRangeAddress(1, 2,i_3, i_3++);
            sheet.addMergedRegion(region);
        }
        //循環添加數據
        for (int j = 0; j < dataList.size(); j++) {
            //創建單元格對象
            //設置數據第一行
            XSSFRow row2 = sheet.createRow(j+3);
            row2.setHeightInPoints(18);//設置行高
            //添加父類數據
            int dataCol = 0;
            for (String s : fatTitle.keySet()) {
                cell= row2.createCell(dataCol);
                cell.setCellValue(dataList.get(j).get(s).toString());
                cell.setCellStyle(SheetStyle.getTextCellStyle(workbook));
                dataCol++;
            }
            //添加子類數據
            List<Map> lis = (List<Map>) dataList.get(j).get("porList");
            //根據二級子標題創建匯總集合
            Map<String,Object> sumMap = sonTitleTow;
            for (Map map : lis) {
                for (String s : sonTitle) {
                    //查找和標題行對應的數據
                    if(map.get(s)!=null){
                        for (String str : sonTitleTow.keySet()) {
                            cell = row2.createCell(dataCol);
                            cell.setCellValue( Double.valueOf(map.get(str).toString()));
                            cell.setCellStyle(SheetStyle.getNumCellStyle(workbook));
                            try{
                                sumMap.put(str,Double.valueOf(sumMap.get(str).toString())+Double.valueOf(map.get(str).toString()));
                            }catch (NumberFormatException e){
                                sumMap.put(str,Double.valueOf(map.get(str).toString()));
                            }
                            dataCol++;
                        }
                        break;
                    }
                }
            }
            /**
             * 添加匯總數據
             */
            for (String str : sonTitleTow.keySet()) {
                cell = row2.createCell(dataCol);
                cell.setCellValue(Double.valueOf(sumMap.get(str).toString()));
                cell.setCellStyle(SheetStyle.getNumCellStyle(workbook));
                dataCol++;
            }
        }
        workbook.setSheetName(0, "測試導出");//設置sheet的Name
        //文檔輸出
        FileOutputStream out = new FileOutputStream("D:/excel/原生poi.xlsx");
        workbook.write(out);
        out.close();
    }

5、測試導出

 List<Demo1> demo1List = new ArrayList<>();
    //父類標題
    Map<String,Object> fatTitle = new HashMap<>();
    //子類一級標題
    List<String> sonTitle = new ArrayList<>();
    //子類二級標題
    Map<String,Object> sonTitleTow = new HashMap<>();
    //數據行
    List<Map<String,Object>> dataList = new ArrayList<>();
    @Before
    public  void testBefore() {
        fatTitle.put("name","姓名");
        fatTitle.put("age","年齡");
        sonTitleTow.put("money","金額");
        sonTitleTow.put("number","數量");
        for (int i = 0; i < 10; i++) {
            Demo1 demo = new Demo1();
            List<Demo2> lis = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                Demo2 demo2 = new Demo2();
                demo2.setName("項目" + j);
                demo2.setMoney((float) (i + j * 3.5));
                demo2.setNumber((i + 1) * 15);
                lis.add(demo2);
            }
            demo.setDemo2(lis);
            demo.setId(i);
            demo.setName("醫院" + i);
            demo.setAge(100 - i);
            demo1List.add(demo);
        }
        demo1List.forEach(demo1 -> {
            Map<String, Object> map = new HashMap<>();
            demo1.getDemo2().forEach(demo2 -> {
                sonTitle.remove(demo2.getName());
                sonTitle.add(demo2.getName());
            });
        });
        demo1List.forEach(demo1 -> {
            Map<String, Object> map = new HashMap<>();
            map.put("name", demo1.getName());
            map.put("age", demo1.getAge());
            List<Map> porList = new ArrayList<>();
            for (String s : sonTitle) {
                Map<String, Object> porMap = new HashMap<>();
                porMap.put(s,s);
                //判斷是否找到的標志
                boolean isFind = false;
                for (Demo2 demo2 : demo1.getDemo2()) {
                    if (demo2.getName().equals(s)) {
                        porMap.put("money", demo2.getMoney());
                        porMap.put("number", demo2.getNumber());
                        isFind = true;
                        break;
                    }
                }
                //找不到給其添加0進行補位
                if (!isFind) {
                    porMap.put("money", 0);
                    porMap.put("number", 0);
                }
                porList.add(porMap);
                map.put("porList", porList);
            }
            dataList.add(map);
        });
    }

    /**
     * 1、創建工作薄對象
     * 2、創建工作表(sheet)對象
     * 3、創建行
     * 4、創建單元格
     * 5、填充數據
     * 6、設置格式
     * 7、合並單元格
     * @throws IOException
     */

    @Test
    public void testExcel() throws IOException {
        ExcelExport.outExcel(fatTitle,sonTitle,sonTitleTow,dataList);
    }

6、導出效果

 

 7、前端點擊下載時

public void dataExport(@RequestBody Map<String,Object> params, HttpServletResponse response){
        XSSFWorkbook workbook = service.dataExport(params);
        SXSSFWorkbook workBook = new SXSSFWorkbook(1000);//內存中最多存放一千條數據,防止內存溢出
        try {
            Date day=new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String name = params.get("title").toString()+ df.format(day);
            String codedFileName = new String(name.getBytes("gbk"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + codedFileName + ".xlsx");
            // 響應類型,編碼
            response.setContentType("application/octet-stream;charset=UTF-8");
            // 形成輸出流
            OutputStream osOut = response.getOutputStream();
            // 將指定的字節寫入此輸出流
            workbook.write(osOut);
            // 刷新此輸出流並強制將所有緩沖的輸出字節被寫出
            osOut.flush();
            // 關閉流
            osOut.close();
            /*
             * dispose of temporary files backing this workbook on disk 處理在磁盤上備份此工作簿的臨時文件
             * SXSSF分配臨時文件,您必須始終清除顯式,通過調用dispose方法
             */
            workBook.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 


免責聲明!

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



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