Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert POI HSSFWorkbook to bytes?

Calling Simple toBytes() does produce the bytes but exel throws Warning.

Lost Document information

Googling around gave me this link and looking at Javadocs for worksheet and POI HOW-TO say similar things . Basically I can not get Bytes without loosing some information and should use the write method instead.

While write does work fine I really need to send the bytes over . Is there any way I can do that ? That is get the bytes with out getting any warning .

like image 442
Shahzeb Avatar asked Apr 17 '12 07:04

Shahzeb


People also ask

What is HSSFWorkbook in Java?

public final class HSSFWorkbook extends POIDocument implements Workbook. High level representation of a workbook. This is the first object most users will construct whether they are reading or writing a workbook. It is also the top level object for creating new sheets/etc.

What is the use of XSSFWorkbook?

XSSFWorkbook It is a class that is used to represent both high and low level Excel file formats. It belongs to the org.


1 Answers

As that mailing list post said

Invoking HSSFWorkbook.getBytes() does not return all of the data necessary to re- construct a complete Excel file.

You can use the write method with a ByteArrayOutputStream to get at the byte array.

ByteArrayOutputStream bos = new ByteArrayOutputStream(); try {     workbook.write(bos); } finally {     bos.close(); } byte[] bytes = bos.toByteArray(); 

(The close call is not really needed for a ByteArrayOutputStream, but imho it is good style to include anyway in case its later changed to a different kind of stream.)

like image 182
Jörn Horstmann Avatar answered Oct 19 '22 01:10

Jörn Horstmann