POI Excel導出自適應列寬


思路:只需要傳入Sheet 即可計算,計算方式為,循環行后再循環列,然后Map記錄列數,每個key就是每列的索引,循環時每列數據的替換上次記錄最大長度,並計算寬度。

ps:Excel有自動列寬方法(sheet.autoSizeColumn(列索引,short類型); //調整第一列寬度)也可以用,並且效率肯定是高於以下方法的,如果數據量非常大請忽略以下方法!

使用方法:在你的Excel文件的所有數據渲染完成后並且在寫出瀏覽器或本地文件夾之前調用這個方法即可!

    public static void cellSetWidth(Sheet sheet) {
        ///獲取行
        int lastRowNum = sheet.getLastRowNum();
        Map<Integer, Integer> dataLen = new HashMap<>();
        // 循環每行 這兒循環有問題導致的  sheet size明明是3,但是獲取的lastRowNum 是2  所以最后一行沒去計算被忽略了-----ok
        for (int i = 0; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            // 每列
            short lastCellNum = row.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++){
                // 列值
                String cellValue = row.getCell(j).getStringCellValue();
                // 長度小於lastCellNum
                if(dataLen.size() < lastCellNum){
                    dataLen.put(j, StringUtils.isBlank(cellValue) ? 0 : cellValue.getBytes().length);
                }else {
                    Integer valLen = dataLen.get(j);
                    if(cellValue.length() > valLen){///內容值 》 上一次記錄的最大值
                        dataLen.put(j, cellValue.getBytes().length);
                    }
                }
            }
        }
        // 到這里就記錄完了所有最大長度
        // 取出key和value值,開始計算
        Set<Map.Entry<Integer, Integer>> entryseSet = dataLen.entrySet();
        for (Map.Entry<Integer, Integer> entry : entryseSet) {
            int columnWidth = entry.getValue();//單元格占的字節數
            if (columnWidth > 33){
                sheet.setColumnWidth(entry.getKey(), columnWidth * 140 + 1950);
            } else {
                sheet.setColumnWidth(entry.getKey(), columnWidth + 3450);
            }
        }
    }

 


免責聲明!

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



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