2013-05-07 78 views
1

我正在使用POI 3.9 & jdk1.6.0_14。autoSizeColumn POI Java未正常工作

我正在使用下面的代碼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); 

,但仍然沒有解決。

+1

您是否在所生成的系統上使用了呈現+可用於Java的所有字體檔案? – Gagravarr 2013-05-07 15:22:40

+0

是的,它使用Arial字體,它存在於Windows/Font中。生成的文件也有Arial字體。 – Soheb 2013-05-07 15:37:02

+0

雖然Java看到了嗎?列的大小是非常依賴於字體的,如果Java沒有訪問正確的字體,它不能正確計算寬度... – Gagravarr 2013-05-07 16:01:01

回答

0

我遇到了你所描述的確切問題,並且能夠通過上面的一些註釋(也是here)中建議的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);