将数据写入Excel工作表java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19361115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write data into Excel sheet java
提问by java_beginner31
I have 3 lists namely list1, list2 and list3. And I want to display these lists in an excel sheet as 3 columns. For example the values in list 1 should be displayed in the first column of Excel sheet. I am adding all the 3 lists to a final list as below and able to display them as separate rows and no idea how can i display as columns. I am using apachepoi.
我有 3 个列表,即 list1、list2 和 list3。我想在 Excel 工作表中将这些列表显示为 3 列。例如,列表 1 中的值应显示在 Excel 工作表的第一列中。我将所有 3 个列表添加到最终列表中,如下所示,并且能够将它们显示为单独的行,但不知道如何显示为列。我正在使用 apachepoi。
List<List> finalList = new ArrayList<List>();
finalList .add(list1);
finalList .add(list2);
WritingToExcelFile(List<List> l1) throws Exception { //passing finalList here
try {
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2 = l1.get(j);
for (int k = 0; k < l2.size(); k++) {
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
采纳答案by Gagravarr
Assuming your lists are all the same size, why not something like:
假设您的列表大小相同,为什么不是这样的:
Sheet s = wb.createSheet();
for (int i=0; i<firstList.size(); i++) {
Row r = s.createRow(i);
r.createCell(0).setCellValue( list1.get(i) );
r.createCell(1).setCellValue( list2.get(i) );
r.createCell(2).setCellValue( list3.get(i) );
}
Add extra error handling if your lists might not be the same length, and extra logic if you need to do formatting / dates / etc for the list contents
如果您的列表长度可能不同,请添加额外的错误处理,如果您需要对列表内容进行格式化/日期/等操作,请添加额外的逻辑