天天看點

解決POI導出Excel單元格内容換行問題

  1. 建議使用hutool工具類來實作,maven依賴。
<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.2.4</version>
        </dependency>
           
  1. 使用方式demo,這裡面使用了hutool工具類的自動換行和設定列值的方法可以讓你少寫很多很多代碼
public static void main(String[] args) throws IOException {
        collapseRow();
    }

    private static void collapseRow() throws IOException {
        try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) {
            SXSSFSheet sheet = workbook.createSheet("new sheet");
            //提前建立好樣式,如果你在for循環内設定樣式的話,樣式對象是有限的會導緻有些樣式缺失但不報錯的問題。一定要注意!!!!
            StyleSet styleSet = new StyleSet(workbook);
            //設定邊框和邊款顔色
            styleSet.setBorder(BorderStyle.THIN, IndexedColors.PINK);
            //單元格内容自動換行
            styleSet.setWrapText();
            ArrayList<String> titleList = CollUtil.newArrayList("編号", "建立時間", "數量", "是否正确", "詳細内容", "名稱");
            int lastRowNum = 0;
            Row row = RowUtil.getOrCreateRow(sheet, lastRowNum++);
            //設定表格
            int cellNum = 0;
            for (String titleName : titleList) {
                //設定單元格内容的時候直接将樣式代入就可以了
                CellUtil.setCellValue(row.createCell(cellNum++), titleName, styleSet.getHeadCellStyle());
            }
            List<Map<String, Object>> dataList = new ArrayList<>();
            Map<String, Object> resultMap = new LinkedHashMap<>();
            resultMap.put("code", "C01");
            resultMap.put("createTime", LocalDate.now());
            resultMap.put("qty", 2000);
            resultMap.put("isStop", true);
            resultMap.put("id", "窗前明月光,疑似地上霜。舉頭望明月,低頭思故鄉。");
            resultMap.put("name", "哒哒");
            dataList.add(resultMap);

            resultMap = new LinkedHashMap<>();
            resultMap.put("code", "C02");
            resultMap.put("createTime", LocalDate.now());
            resultMap.put("qty", 20000);
            resultMap.put("isStop", false);
            resultMap.put("id", "日照香爐生紫煙,遙看瀑布挂前川。飛流直下三千尺,疑是銀河落九天。");
            resultMap.put("name", "滴滴");
            dataList.add(resultMap);
            //填充資料
            for (Map<String, Object> map : dataList) {
                row = RowUtil.getOrCreateRow(sheet, lastRowNum++);
                cellNum = 0;
                for (String key : map.keySet()) {
                    Object value = map.get(key);
                    Cell cell = CellUtil.getOrCreateCell(row, cellNum++);
                    //設定單元格内容的時候直接将樣式代入就可以了
                    CellUtil.setCellValue(cell, value, styleSet, false);
                }
            }

            try (FileOutputStream fileOut = new FileOutputStream("gideonYeung.xlsx")) {
                workbook.write(fileOut);
                log.error("導出成功。");
            } finally {
                workbook.dispose();
            }
        }
    }
           
  1. 導出的結果。
    解決POI導出Excel單元格内容換行問題