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);
            }
        }
    }

 

posted @ 2021-12-28 15:35  明年上初中  阅读(878)  评论(0编辑  收藏  举报