for (int col = 0; col < 20; ++col) {
detailSheet.autoSizeColumn(col);//只支持英文和数字
int columnWidth = detailSheet.getColumnWidth(col) / 256;
for (int row = 0; row < rowIndex; ++row) {
Cell cell = detailSheet.getRow(row).getCell(col);//如果有合并单元格,就会有getCell()==null的情况,需要createCell();
if (cell == null) {
cell = detailSheet.getRow(row).createCell(col);
}
intlength = cell.toString().getBytes("GBK").length;
if (columnWidth < length + 1) {
columnWidth = length + 1;
}
}
detailSheet.setColumnWidth(col, columnWidth * 256); //对中文列调整列宽
}
2019-04-08
今天poi导出的时候发现了个问题。当某一列存在空值的单元格时,autoSizeColumn()
方法会报空指针。
我遇到的是 null 时报错,空字符串不报错,所以我将null值替换成空字符串"“时可行。但在看其他人博客的时候发现,空字符串也会报错,所以可以替换成” ",即加个空格。