Writing a List instance to Excel file - Apache POI

2019-06-08 11:12发布

问题:

I have a List of String objects that are pipe delimited. something like this:

String1|String2|String3
String4|String5|String6
...

Using Apache POI as excel library, is it possible to iterate over entire List writing out the string object as each row in the excel file? i.e. something like:

for (String inst : <List instance>)
       <sheetInstance>.write(inst)

i.e. output the string directly to the excel as a row entry rather than setting each cell value with a string i.e.

setting row 1, cell 1 = String1
setting row 1, cell 2 = String2
setting row 1, cell 3 = String3
setting row 2, cell 1 = String4 ...

Currently, it looks like I need to set individual cells to each value.

回答1:

You need to split the String into an array in order to fill the cells, like this:

for (short rowIndex = 0; rowIndex < stringList.length(); rowIndex++) {
    Row row = sheet.createRow(rowIndex);
    String[] cellValues = stringList.get(rowIndex).split("|");
    for (int colIndex = 0; colIndex < cellValues.length; colIndex++) {
        Cell cell = row.createCell(colIndex);
        cell.setCellValue(cellValues[colIndex]);
    }
}