【问题标题】:autoSizeColumn POI Java is not working properlyautoSizeColumn POI Java 无法正常工作
【发布时间】:2022-01-31 15:02:45
【问题描述】:

我正在使用 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);

但仍然没有解决方案。

【问题讨论】:

  • 在您生成文件的系统上,您使用的所有字体是否都存在 + 可供 Java 使用?
  • 是的,它使用 Arial 字体,该字体存在于 Windows/Font 中。生成的文件也有 Arial 字体。
  • Java 看到了吗?列大小非常依赖于字体,如果 Java 无法访问正确的字体,则无法正确计算宽度...
  • U 也可以为每个标题单元格使用 setColumnWidth。因此它将为所有单元格应用大小。

标签: java apache-poi


【解决方案1】:

我遇到了您所描述的确切问题,并且能够通过上面某些 cmets 中的建议通过 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 2017-02-17
    • 2017-03-30
    • 2015-02-20
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多