如何使用String List编写Excel文件

时间:2016-06-12 18:21:46

标签: java excel apache-poi

我想写一个excel文件。所有写作细节都包含一个列表。并将其设置为方法的输入参数。 请告诉我最好的方法。

public static void writeExcelFile(List<String> combineLists){
          XSSFWorkbook workbook = new XSSFWorkbook(); 
          XSSFSheet sheet = workbook.createSheet("Employee Data");
|
|

}

输入列表:

1 个答案:

答案 0 :(得分:3)

您的图片显示List中有一个字符串列表,其中您的Input参数仅将列表作为参数。所以我假设它是List<List<String>>

   FileOutputStream out = new FileOutputStream(new File("demo.xlsx"));
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("Employee Data");
//I am creating and adding list just for illustration purpose only
            List<String> l1 = new ArrayList<String>();
            l1.add(" l1 1");
            l1.add("l1 2");
            List<String> l2 = new ArrayList<String>();
            l2.add(" l2 1");
            l2.add("l2 2");
            List<List<String>> list = new ArrayList<List<String>>();
            list.add(l1);
            list.add(l2);
            Iterator <List<String>>i = list.iterator();
            int rownum=0;
            int cellnum = 0;
            while (i.hasNext()) {
                List<String> templist = (List<String>) i.next();
                Iterator<String> tempIterator= templist.iterator();
                Row row = sheet.createRow(rownum++);
                cellnum = 0;
                while (tempIterator.hasNext()) {
                    String temp = (String) tempIterator.next();
                        Cell cell = row.createCell(cellnum++);
                                cell.setCellValue(temp);

                    }

                }
            workbook.write(out);
            out.close();
            workbook.close();

我希望这会有所帮助。