I wish to convert HSSFWorkbook into a CSV file format and then write it to ServletOutputStream where I have setContentType as text/x-csv. Thanks in advance.
+3
A:
There is no existing code AFAIK. Iterate over all the cells in the first sheet and write them out. Make sure you properly escape the field separators and the quotes.
Aaron Digulla
2009-10-09 09:02:51
A:
I wrote below piece of code which pretty much does the job for me:
ServletOutputStream serv = response.getOutputStream(); response.setContentType("text/x-csv"); response.addHeader("Content-Disposition", "attachment; filename=ListofContracts.csv"); HSSFSheet sheet = wb.getSheetAt(0);
for (int i=0;i <= sheet.getLastRowNum() ;i++ ) {
HSSFRow row = sheet.getRow(i);
for (short j=0;j<= row.getLastCellNum();j++ ) {
HSSFCell cell= row.getCell(j);
strBuff.append(cell.getStringCellValue()+" , ");
}
}
serv.write(strBuff.toString().getBytes());
Ravi Gupta
2009-10-10 06:27:21
I think this has a issue if the cell value contains a ',' the CSV separator used in this sample. 'Aaron Digulla' has already noted the point above
Arun P Johny
2010-02-04 12:56:10