我使用的是 POI 3.9 和 jdk1.6.0_14。
我使用下面的代码来自动调整列大小,但问题是当生成Excel时,它没有完全自动调整为列,当我双击列之间时,当时我可以看到该列正确地自动调整大小。
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
HSSFSheet thisSheet = workbook.getSheetAt(i);
log.info("Last row : "+thisSheet.getLastRowNum());
HSSFRow rowexcel = thisSheet.getRow(thisSheet.getLastRowNum());
// Auto sizing columns
for (short j = 0; j < rowexcel.getLastCellNum(); j++) {
workbook.getSheetAt(i).autoSizeColumn(j);
}
// Freezing the top row
workbook.getSheetAt(i).createFreezePane(0, 1);
}
而不是
HSSFRow rowexcel = thisSheet.getRow(thisSheet.getLastRowNum());
我也尝试过顶行
HSSFRow rowexcel = thisSheet.getRow(0);
但仍然没有解决。
最佳答案
我遇到了您所描述的确切问题,并且能够按照上面一些评论中的建议通过 Cell
样式显式设置字体(也为 here ),从而取得了一些成功。
但是,我注意到的一件事是 autoSizeColumn
仍然没有考虑所有单元格的宽度。特别是,我有一行单元格,它们基本上是描述每列数据的列标题。这些单元格已成功应用自定义Font
,但在运行autoSizeColumn
时仍未考虑列的宽度。存在差异,但我认为它们是无关紧要的。例如,标题的单元格类型与列中其他数据的不同...并且单元格标题应用了不同的颜色以使它们脱颖而出。
话虽如此,尝试创建一个仅应用一组非常基本的单元格样式的工作表,然后尝试从那里进行调整:
// Let's test with Arial, 10pt
Font testFont = workbook.createFont();
testFont.setFontName("Arial");
testFont.setFontHeightInPoints((short)10);
// We'll apply a very bare-bones style to our cells that just applies the Font
CellStyle testCellStyle = workbook.createCellStyle();
testCellStyle.setFont(testFont);
// Your real data cell creation would go here instead of my dummy code:
CreationHelper creationHelper = workbook.getCreationHelper();
Row testRow = thisSheet.createRow(0);
int currentColumn = 0;
Cell testCell = testRow.createCell(currentColumn++);
testCell.setCellStyle(testCellStyle);
testCell.setCellType(Cell.CELL_TYPE_STRING);
testCell.setCellValue(creationHelper.createRichTextString("Cell Data Goes Here");
testCell = testRow.createCell(currentColumn++);
testCell.setCellStyle(testCellStyle);
testCell.setCellType(Cell.CELL_TYPE_STRING);
testCell.setCellValue(creationHelper.createRichTextString("Your Real Code Won't Be This Redundant :)");
最后一个想法,如果 autoSizeColumn
仍然对列宽做不幸或不一致的事情,您可以添加一个安全网以确保列不会小于默认值:
int origColWidth = thisSheet.getColumnWidth(currentColumn);
thisSheet.autoSizeColumn(currentColumn);
// Reset to original width if resized width is smaller than default/original
if (origColWidth > thisSheet.getColumnWidth(currentColumn))
thisSheet.setColumnWidth(currentColumn, origColWidth);
关于java - autoSizeColumn POI Java 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16420926/