2013-05-07 131 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);