Apache POI autoSizeColumn调整大小不正确

Jaw*_*212 26 java apache excel apache-poi

我在java中使用Apache POI来创建excel文件.我填写数据然后尝试自动调整每列,但是大小总是错误的(我认为一致).前两行总是(?)完全折叠.当我在excel中自动调整列时,它可以完美地工作.

没有写入空白单元格(我相信),调整大小是我做的最后一件事.

这是相关的代码:这是一个没有错误处理等的简化版本.

public static synchronized String storeResults(ArrayList<String> resultList, String file) {
    if (resultList == null || resultList.size() == 0) {
        return file;
    }
    FileOutputStream stream = new FileOutputStream(file);

    //Create workbook and result sheet
    XSSFWorkbook book = new XSSFWorkbook();
    Sheet results = book.createSheet("Results");

    //Write results to workbook
    for (int x = 0; x < resultList.size(); x++) {
        String[] items = resultList.get(x).split(PRIM_DELIM);

        Row row = results.createRow(x);
        for (int i = 0; i < items.length; i++) {
            row.createCell(i).setCellValue(items[i]);
        }
    }

    //Auto size all the columns
    for (x = 0; x < results.getRow(0).getPhysicalNumberOfCells(); x++) {
        results.autoSizeColumn(x);
    }

    //Write the book and close the stream
    book.write(stream);
    stream.flush();
    stream.close();

    return file;
}
Run Code Online (Sandbox Code Playgroud)

我知道有一些类似的问题,但大多数只是在填写数据之前的大小调整的情况.少数不是更复杂/没有答案.

编辑:我尝试使用几种不同的字体,但它没有用.这并不太令人惊讶,因为无论字体是什么,所有列都应该完全折叠或者不应该完全折叠.

此外,因为字体问题出现了,我正在Windows 7上运行该程序.

已解决:这是一个字体问题.我找到的唯一字体是Serif.

Sha*_*ded 13

只是为了回答我的评论.行无法正确调整大小,因为Java不知道您尝试使用字体链接的字体应该有用,如果您想要将新字体安装到Java中,那么您可以使用更高级的东西.它还具有Java知道的默认字体列表.

很高兴这有帮助,你解决了你的问题!


Seb*_*ien 7

这可能与此POI Bug有关,该错误Java Bug JDK-8013716有关:Calibri和Cambria Fonts的渲染器自更新45以来失败.

在这种情况下,更改字体或使用高于6u45/7u21的JRE应该可以解决问题.

您还可以通过使用此类代码来调整问题并避免列完全崩溃 __CODE__


小智 6

我也遇到了这个问题,这是我的解决方案.

脚步:

  1. 创建工作簿
  2. 创建电子表格
  3. 创建行
  4. 创建/设置字体为"Arial"
  5. 用字体创建/设置样式
  6. 使用值和样式创建/设置单元格
  7. autoSizeColumn
  8. 创建文件

码:

// initialize objects
XSSFWorkbook workbook = new XSSFWorkbook(); 
XSSFSheet spreadsheet = workbook.createSheet(sheetName);
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;

// font/style
XSSFFont font = workbook.createFont();
font.setFontName("Arial");
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);

// create/set cell & style
cell = row.createCell(0);
cell.setCellValue("New Cell");
cell.setCellStyle(style);

// auto size
spreadsheet.autoSizeColumn(0);

// create file
File aFile = new File("Your Filename");
FileOutputStream out = new FileOutputStream(aFile);
workbook.write(out);
Run Code Online (Sandbox Code Playgroud)

资源:

http://www.tutorialspoint.com/apache_poi/index.htm