2

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

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);

Can anyone help me get this done?

1
  • Split, get the first String and make it the cat and after that loop the items and put it into a String Builder. Commented Oct 12, 2018 at 12:34

2 Answers 2

2

What you need to do is use createRow() the first time to... create the row, and getRow() for all subsequent access. That way, you'll get the row already in the worksheet object instead of creating a new one. getRow() returns null if the row doesn't exist, so you can do the equivalent of this:

XSSFRow row = outputSheet.getRow(rowNumValue) ? outputSheet.getRow(rowNumValue) : outputSheet.createRow(rowNumValue);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
            ...
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.