poi使用autoSizeColumn调整列宽踩坑

6,514 阅读2分钟

业务场景

导出的excel表中,单元格空隙太大,导出后每次都要调整。

前期考虑

采用

poi中的
autoSizeColumn()方法进行解决。

/** Adjusts the column width to fit the contents.  
 *  This process can be relatively slow on large sheets, so this should  
 *  normally only be called once per column, at the end of your  
 *  processing.  
 *  
 *  @param column the column index  
 */
public void autoSizeColumn(int column) {
     autoSizeColumn(column, false); 
}

上面是该方法具体实现,通过注释可以知道该方法在大的excel当中实现过程比较慢,因此在处理结束时每列只调用一次。

起因

使用该方法之后发现未包含中文的列宽度自动调整了,而包含中文的列宽度则未更改。

分析

可能因为程序中英文识别问题导致列宽不能自适应。单独创建一个方法进行中文字符个数判断并重新分配列宽。

解决

//自适应宽度(中文支持)
private void setSizeColumn(XSSFSheet sheet, int size) {    
    for (int columnNum = 0; columnNum < size; columnNum++) {
        //获取列宽
        int columnWidth = sheet.getColumnWidth(columnNum);
        for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
            XSSFRow currentRow;
            //当前行未被使用过
            if (sheet.getRow(rowNum) == null) {
                currentRow = sheet.createRow(rowNum);
            } else {
                currentRow = sheet.getRow(rowNum);
            }
            if (currentRow.getCell(columnNum) != null) {
                XSSFCell currentCell = currentRow.getCell(columnNum);
                if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                    int count = 0;//汉字数量
                    String regEx = "[\\u4e00-\\u9fa5]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(currentCell.getStringCellValue());
                    int len = m.groupCount();
                    //获取汉字个数
                    while (m.find()) {
                        for (int i = 0; i <= len; i++) {
                            count = count + 1;
                        }
                    }
                    //因为程序中将汉字编译成一个字符,因此我们在该列字符长度的基础上加上汉字个数计算列宽
                    int length = (currentCell.getStringCellValue().length()+count)*256;
                    if (columnWidth < length) {
                        columnWidth = length;
                    }
                }
            }
        }
        //设置列宽
        sheet.setColumnWidth(columnNum, columnWidth);
    }
}


通过上述代码就完美解决了包含中文列列宽自动调整达不到预期效果的bug。


有什么不对的地方欢迎各位大佬及时指出,有什么问题需要讨论也可以通过一下联系方式联系我一块探讨。

QQ:2289949405

微信:17638834978

最后奉上一直激励我的一句话:

坚持做自己懒得做的事情,就能得到别人想得到却得不到的东西!