STheFox
STheFox

Reputation: 1498

Java Apache POI: create excel with cell values auto typed

Is there any functionality to auto fill the data in the cells with the correct type? Now I have to manually set the types, f.e. String or Integer.

Code now is:

for (String colName : headerNames) {
    dataRow.createCell(colIndex++).setCellValue(rs.getString(colName));
}

At this moment I have to declare for each cell separately what type to use with rs.getString(colName). As the data contains both Strings as Integers, it would be handy if they could me automatically typed.

Upvotes: 0

Views: 874

Answers (1)

centic
centic

Reputation: 15872

There is no functionality inside POI and it would be hard to provide one for Dates as there are a myriad of different date formats in use, but it should be fairly easy to come up with a helper method that you can use in your project, e.g. something like

public static void setCellValue(Cell cell, String value) {
    try {
        cell.setCellValue(Double.parseDouble(value));
    } catch (NumberFormatException e) {
        // not a number, let's use String
        cell.setCellValue(value);
    }
}    

This can easily be extended to a date-format as well if you know the actual format that the date is coming in.

Upvotes: 1

Related Questions