Hutool工具类ExcelWriter导出excel列宽自适应问题解决

前言:

因为项目中需要使用到ExcelWriter导出excel的列宽自适应,下面为解决该问题的经过,希望可以对遇到同样问题的开发者有所帮助。 一、通过查询Hutool官方的api文档发现autoSizeColumn()方法 但是,在代码中使用该方法后发现并没有起作用。 二、通过搜索发现其他开发者使用Sheet强制转换为SXSSFSheet,后再调用改方法可以成功设置自适应。

SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();
        sheet.trackAllColumnsForAutoSizing();
        writer.autoSizeColumnAll();

再次尝试使用后报错: java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFSheet cannot be cast to org.apache.poi.xssf.streaming.SXSSFSheet 三、自定义方法

/**
     * 自适应宽度(中文支持)
     * @param sheet
     * @param size 因为for循环从0开始,size值为 列数-1
     */
    public static void setSizeColumn(Sheet sheet, int size) {
          
   
        for (int columnNum = 0; columnNum <= size; columnNum++) {
          
   
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
          
   
                Row currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
          
   
                    currentRow = sheet.createRow(rowNum);
                } else {
          
   
                    currentRow = sheet.getRow(rowNum);
                }

                if (currentRow.getCell(columnNum) != null) {
          
   
                    Cell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
          
   
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
          
   
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }

问题解决,可以实现列宽自适应。 效果展示: 大神的解决办法: 根据大神的评论,我调用的位置可能不对,要在写出内容后调用才会生效。

经验分享 程序员 微信小程序 职场和发展