javaapache-poixssf

Java Apache POI XSSFWorkbook saving column data as text instead of numeric


I have this piece of code which generates an excel file which looks something like this:

public static void generateExcel(List<Results> results, String outputPath)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    Workbook workbook = new XSSFWorkbook();
    var sheet = workbook.createSheet("Report");

    String[] headerValues = {"Name", "Type", "Price"};


    Row headerRow = sheet.createRow(0);
    for (int i = 0; i < headerValues.length; i++) {
        headerRow.createCell(i).setCellValue(headerValues[i]);
    }

    for (var i = 0; i < results.size(); i++) {
        var row = sheet.createRow(i + 1);
        Results summary = results.get(i);
        int colNum = 0;
        for (var header : headerValues) {
            String propertyName = "get" + header;
            Method method = Results.class.getMethod(propertyName);
            Object value = method.invoke(summary);

            if (value != null) {
                row.createCell(colNum).setCellValue(value.toString());
            } else {
                row.createCell(colNum).setCellValue("");
            }
            colNum++;
        }

    }

    for (var i = 0; i < headerValues.length; i++) {
        sheet.autoSizeColumn(i);
    }

    String path = Objects.requireNonNullElse(outputPath, "report.xlsx");
    writeToFile(workbook, path, LOG);
}

There is a loop going through the list of header values and invoking the methods which were created previously e.g getName() and then creating an excel file with the data.

The problem I am facing now is that the price column is set as text in the excel file, which makes it difficult to filter instantly without conversion in excel.

How do I set the column to numerical style ?

I've tried this snippet of code below to no avail.

DataFormat fmt = workbook.createDataFormat();
CellStyle numericStyle = sheet.getWorkbook().createCellStyle();
numericStyle.setDataFormat(fmt.getFormat("0.00"));
sheet.setDefaultColumnStyle(15, numericStyle);

The excel file is still created, but the values are still seen on the left hand side in the excel and must be converted to numbers before filtering can take place.


Solution

  • Cell format is independent of cell TYPE.

    Use the two-argument version of XSSFRow.createCell(int columnIndex, CellType type) and specify the appropriate type.

    Also, next time please study the Javadoc before posting here.