如何使用Apache poi逐列编写

时间:2017-11-16 12:27:23

标签: java excel apache-poi

我有一张如下地图:

Map<String, Map<String, List<String>>> finalDataSet = new LinkedHashMap<>();

它包含以下数据:

{Name1={CurrentUserStory=[AB-1413, AB-1504], CUS_Status=[In Testing, Ready for Deployment], SubTask=[AB-1547, AB-1508], ST_Status=[In Development, Done], TimeSpent=[19800, 23400]},Name2={CurrentUserStory=[AB-1377, AB-149],CUS_Status=[Ready for Testing, Ready for Development],SubTask=[AB-1545, AB-1510], ST_Status=[Ready for Testing, Closed],TimeSpent=[25200, 5400]}}

以上数据我想以下面的格式写入excel。

enter image description here

当我尝试将这些数据写入excel时,只有“TimeSpent”列正在写入并且所有列都是空的。这是我的代码:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sh = wb.createSheet("CSG_Report");
Row row = sh.createRow(2);
for (Map.Entry<String, Map<String, List<String>>> m : finalDataSet.entrySet()) {
    int col=1;
    row= sh.createRow(index);
    int userindex=index;
    for(Map.Entry<String, List<String>> innerMap:m.getValue().entrySet())
    {
        index = userindex;
        List<String> val=innerMap.getValue();
        row= sh.createRow(index);
        for (String string : val) {
            row= sh.createRow(index);
            row=sh.getRow(index);
            Cell cell = row.createCell(col);
            cell.setCellValue(string);
            index++;
        }
        col++;
    }
}
FileOutputStream out = new FileOutputStream(new
        File("D:\\Output.xlsx"));
wb.write(out);
out.close();
wb.close();

请帮我完成它。感谢您的帮助。提前致谢。

1 个答案:

答案 0 :(得分:0)

我为我的问题找到了一些解决方案。 这是我的代码......

int columnNum=1;
    int fRow=2;
    List<String> cvals = null;
    for (Map.Entry<String, Map<String, List<String>>> m : finalDataSet.entrySet()) {
        Row row = sh.createRow(fRow);
        Cell cell1=row.createCell(0);
        cell1.setCellValue("Name1");

        for(Map.Entry<String, List<String>> innerMap:m.getValue().entrySet()){
            cvals=innerMap.getValue();

             int tempHeight=cvals.size();
             int temp=fRow;
             for (String cval : cvals) {
                 Row row2;
                 if(sh.getPhysicalNumberOfRows()-1>temp-1)
                    {

                        row2=sh.getRow(temp);
                    }
                    else
                    {
                        row2=sh.createRow(temp);
                    }
                 Cell cell3=row2.createCell(columnNum);
                 cell3.setCellValue(cval);
                 temp=temp+1;
            }
             columnNum=columnNum+1; 
        }
        fRow=fRow+cvals.size();
        columnNum=1;
    }