如何使用Java以列方式在excel中编写数据列表? [英] How to write a list of data in excel in column wise using Java?

查看:43
本文介绍了如何使用Java以列方式在excel中编写数据列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ArrayList 中有一个数据列表,其中包含标题以及与之关联的值.如下图,

I have a list of data in ArrayList which contains the heading as well as the values associated with it. Like below,

Fruits 
Apple 
Orange 
******
Vegetables 
Beans
Carrot 
Brinjal
Cucumber 
******
Colors
Orange 
Blue
Red
Green
Yellow

Now, I want to write the values in `excel` with each heading and the associated values in column-wise. Like below,

Fruits   Vegetable   Colors
Apple    Beans       Orange 
Orange   Carrot      Blue
         Brinjal     Red
         Cucumber    Green
                     Yellow

我正在用 java 编写代码并使用 apache.poi.xssf.usermodel 库来处理 excel 操作.我在这里面临的问题是,当我编写第二个标题和相关值时,第一个标题及其值由于 Row 创建代码而被清除

I'm writing my code in java and using apache.poi.xssf.usermodel library, to handing the excel manipulations. The issue what I'm facing here is, when I'm writing the 2nd heading and the associated values, the first heading and its values are getting cleared due to the Row creation code

XSSFRow row = outputSheet.createRow(rowNumValue);

谁能帮我完成这件事?

推荐答案

可以立即对单个列表进行操作,但使用合理的数据结构更容易.由于每一列可以有不同的行数,制作一个列列表,每列一个行列表.

One could operate immediately on the single list, but it is easier to use a sensible data structure. As every column can have a different number of rows, make a list of columns, every column a list of rows.

List<List<String>> makeColumns(List<String> linearList) {
    List<List<String>> columns = new ArrayList<>();
    int column = 0;
    for (String s : linearList) {
        if (s.startsWith("***")) {
            ++column;
        } else {
            while (column >= columns.size()) {
                columns.add(new ArrayList<>());
            }
            columns.get(column).add(s);
        }
    }
}

现在可以遍历行以填充工作表.

Now one can iterate over the rows to fill the sheet.

List<List<String>> columns = makeColumns(...);
int rows = columns.stream().mapToInt(List::size).max().orElse(0);

for (int rowi = 0; rowi < rows; ++rowi) {
    XSSFRow row = outputSheet.createRow(rowi + 1);
    for (int coli = 0; coli < columns.size(); ++coli) {
        if (rowi < columns.get(coli).size()) {
            String value = columns.get(coli).get(rowi);
            row.createCell(coli);
            ...
        }
    }
}

这篇关于如何使用Java以列方式在excel中编写数据列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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