I am writing a java program in which I have to take data from XML file and put it into excel file. While doing this I have to create row headers and add data accordingly.
I know how to create column headers. I can do it in following way:
....
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("EDR Raw Data");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Header1");
header.createCell(1).setCellValue("Header2");
header.createCell(2).setCellValue("Header3");
header.createCell(3).setCellValue("Header4");
....
It creates excel file as shown below:
But I want my excel file looks like below:
I am not getting a way to do this. It's not good idea to create required number of rows individually. Is there any way by which we can create a column and add all header in that column?
The way I tried to do this is:
....
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("EDR Raw Data");
sheet.createRow(0).createCell(0).setCellValue("header1");
sheet.createRow(1).createCell(0).setCellValue("header2");
sheet.createRow(2).createCell(0).setCellValue("header3");
sheet.createRow(3).createCell(0).setCellValue("header4");
...
But in my case I have to give 100+ row labels. SO this won't be efficient way.
Add a New Column In this method, we use a loop to go through all rows of the input Excel sheet. For each row, we first find its last cell number and then create a new cell after the last cell.
HSSF (Horrible Spreadsheet Format) − It is used to read and write xls format of MS-Excel files. XSSF (XML Spreadsheet Format) − It is used for xlsx file format of MS-Excel.
Just create one row for each header, and populate the first cell in each!
Something like:
String[] headers = new String[] { "Header1", "Header2", "Header3" };
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("EDR Raw Data");
for (int rn=0; rn<headers.length; rn++) {
Row r = sheet.createRow(rn);
r.createCell(0).setCellValue(headers[rn]);
}
Then when populating your data, do sheet.getRow(rownumber)
to get the existing row, and populate the remaining cells of interest in it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With