[英]autoSizeColumn POI Java is not working properly
我正在使用 POI 3.9 和 jdk1.6.0_14。
我正在使用下面的代碼來autoSizeColumn,但問題是生成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
樣式顯式設置字體來獲得一些成功。
但是,我注意到的一件事是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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.