tags:

views:

342

answers:

3

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
A: 

Check out SuperCSV

fvu
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
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