javaapacheexcelapache-poi

Apache POI autoSizeColumn Resizes Incorrectly


I'm using Apache POI in java to create an excel file. I fill in the data then try to autosize each column, however the sizes are always wrong (and I think consistent). The first two rows are always(?) completely collapsed. When I autosize the columns in excel, it works perfectly.

No blank cells are being written (I believe) and the resizing is the last thing I do.

Here's the relevant code: This is a boiled down version without error handling, etc.

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;
}

I know there are a few questions out there similar, but most of them are simply a case of sizing before filling in the data. And the few that aren't are more complicated/unanswered.

EDIT: I tried using a couple different fonts and it didn't work. Which isn't too surprising, as no matter what the font either all the columns should be completely collapsed or none should be.

Also, because the font issue came up, I'm running the program on Windows 7.

SOLVED: It was a font issue. The only font that I found that worked was Serif.


Solution

  • Just to make an answer out of my comment. The rows couldn't size properly because Java was unaware of the font you were trying to use this link should help if you want to install new fonts into Java so you could use something fancier. It also has the list of default fonts that Java knows.

    Glad this helped and you got your issue solved!