autoSizeColumn 函数本身工作不完美,某些列宽不完全适合其中的数据。因此,我找到了一些适合我的解决方案。
- 为了避免疯狂的计算,让我们把它交给autoSizeColumn()函数:
sheet.autoSizeColumn(<columnIndex>);
- 现在,我们的列按库自动调整大小,但我们不会向当前列宽添加更多内容以使表格看起来很好:
// get autosized column width
int currentColumnWidth = sheet.getColumnWidth(<columnIndex>);
// add custom value to the current width and apply it to column
sheet.setColumnWidth(<columnIndex>, (currentColumnWidth + 2500));
- 完整函数可能如下所示:
public void autoSizeColumns(Workbook workbook) {
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(i);
if (sheet.getPhysicalNumberOfRows() > 0) {
Row row = sheet.getRow(sheet.getFirstRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
sheet.autoSizeColumn(columnIndex);
int currentColumnWidth = sheet.getColumnWidth(columnIndex);
sheet.setColumnWidth(columnIndex, (currentColumnWidth + 2500));
}
}
}
}
P.S. 感谢 Ondrej Kvasnovsky 的功能 https://stackoverflow.com/a/35324693/13087091