使用 Apache POI 逐列写入 [英] Write column by column using Apache POI

查看:51
本文介绍了使用 Apache POI 逐列写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Apache POI逐列编写?

How to write column by column using Apache POI?

我有一个自定义映射,其中的键包含多个值.

I have a custom map in which I have keys containing multiple values.

{a=[1, 2], b=[3, 4, 5]}

现在我想将这些东西写入excel,以a和b作为列名,将它们的值作为单元格值.

Now I want to write these things into excel having a and b as column name and their values as cell value.

Desired Output
a      b
1      3
2      4
       5

我得到的只是使用 Apache POI 逐行写入.任何人都可以建议我的技巧,以便我可以逐列写它?

All I am getting is writing row by row using Apache POI. Can anyone suggest me trick so that I can write it column by column?

推荐答案

我找到了答案,实际上 POI 只支持逐行插入,所以为了逐列插入我应用了这个逻辑

I found answer, actually POI only supports row by row insertion , so to do column by column insertion I applied this logic

   HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("sheet");
    //Create a new row in current sheet
    Row row = sheet.createRow(0);
    //Create a new cell in current row
    for(String key:map.keySet())
    {
        Cell cell1=row.createCell(columnNum);
        cell1.setCellValue(key);
        //System.out.println(map.get(key));
        List<Integer> columnValues = map.get(key);
        int tempHeight=columnValues.size();
        /*if(maxRows<tempHeight)
        {
            maxRows=tempHeight;
        }*/
        int temp=1;
        for(int i:columnValues)
        {
            Row row2;
            //System.out.println("no of rows:"+(sheet.getPhysicalNumberOfRows()-1)+", height:"+tempHeight);
            if(sheet.getPhysicalNumberOfRows()-1>temp-1)
            {
                //System.out.println("take row");
                row2=sheet.getRow(temp);

            }
            else
            {

                //System.out.println("Row inserted");
                row2=sheet.createRow(temp);
            }
            Cell cell2=row2.createCell(columnNum);
            cell2.setCellValue(i);
            temp=temp+1;
        }

        columnNum=columnNum+1;


    }

这篇关于使用 Apache POI 逐列写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆