Writing a List instance to Excel file - Apache POI

好久不见. 提交于 2019-12-08 08:21:24

问题


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


来源:https://stackoverflow.com/questions/11251432/writing-a-list-instance-to-excel-file-apache-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!