views:

247

answers:

2

I've generated an Excel spreadsheet using HSSFWorkbook, then implemented a custom javax.activation.DataSource to attach the spreadsheet to an email. However, upon opening the spreadsheet in Excel, it crashes. Excel can recover some of the data, but it loses most of its formatting.

+1  A: 

When returning an InputStream in the DataSource implementation, make sure you are not using HSSWorkbook.getBytes() as this will only return a specific portion of the spreadsheet (that cannot be used on its own), not the entire file. Use the write() method instead with a ByteArrayOuputStream. For example:

public InputStream getInputStream() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    workbook.write(baos);
    return new ByteArrayInputStream(baos.toByteArray());
}

Just be cautious with the size of the spreadsheet, as this is happening in memory. Consider storing the spreadsheet instead and attaching that using the regular FileDataSource.

HSSFWorkbook.getBytes()

Jordy Boom
A: 

I think the problem is in the POI which does not generate a readable excel file.

liya
Actually, it works quite well for generating Excel sheets. The issue is simply that a method (getBytes()) does not work as expected. And the JavaDoc for the method confirms that.
Jordy Boom