'Dynamically creating rows in Excel sheet with Apache POI
I'm writing a program to read a large xml file and create an excel file from it. The attributes of each node will be the column headers in excel file. I created a Dom object and got the nodelist. I need to iterate through it and for each node, i need to add a row in excel sheet with the node's attributes values as column values. So, when iterating, i need to create rows dynamically. How can i do it? I dont see a functionality to add created rows in apache POI, so far what i have seen is to define new rows everytime. I'm unable to do it since it has more than 5000 entries. Basically what i want to do is:
Node node = null;
HSSFRow datarow = null;
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
datarow = spreadSheet.createRow(i);
//set values for data row here, and add it.
//so in the loop, next time the same variable will be assigned to spreadSheet.createRow(1) etc.
}
I understand that the createRow is invoked from spreadSheet, which will add the row to it. But in the loop, the same variable will be assigned to other rows too, so i think finally i will get only 1 row. Please advice me on this.
Solution 1:[1]
Try the following
Node node = null;
HSSFRow datarow = null;
for (int i = 0; i < nodeList.getLength(); i++) {
// On each loop you get the value of node item
node = nodeList.item(i);
//For every new node list you will create a row
datarow = spreadSheet.createRow(i);
//Finally set the node value to the columns of the newly created Row
}
Hope this helps !!
Solution 2:[2]
createRow
has already created the row in the worksheet and is returning a reference to the newly created row. You will lose this reference on the next loop iteration but it will not remove/override the previous row from the worksheet. You can expect to have the correct number of rows in the end.
int totalRows = 5;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Data");
HSSFRow datarow = null;
for (int i = 0; i <= totalRows; i++) {
datarow = sheet.createRow(i);
datarow.createCell(0).setCellValue(Integer.toString(i));
}
System.out.println("Total Rows: " + sheet.getLastRowNum());
System.out.println("First row cell value: " + sheet.getRow(0).getCell(0).getStringCellValue());
System.out.println("Last row cell value: " + sheet.getRow(totalRows).getCell(0).getStringCellValue());
/*
Total rows: 5
First row cell value: 0
Last row cell value: 5
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Srinivas M.V. |
Solution 2 | Ari |