autoSizeColumn POI Java无法正常工作

时间:2013-05-07 13:56:56

标签: java apache-poi

我正在使用POI 3.9& jdk1.6.0_14。

我使用下面的代码来autoSizeColumn,但问题是当生成excel时,它没有完全自动调整到列,当我在列之间双击时,那时我可以正确地看到该列是自动调整的。 / p>

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 个答案:

答案 0 :(得分: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);