60

Calling Simple toBytes() does produce the bytes, but Excel 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 cannot get Bytes without losing 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 without getting any warning.

Alexandr
  • 243
  • 2
  • 3
  • 15
Shahzeb
  • 4,745
  • 4
  • 27
  • 40

2 Answers2

123

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.)

Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
23

How about:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
byte[] xls = baos.toByteArray();

In order to get a full excel file out, you must call the write(OutputStream) method. If you want bytes from that, just give a ByteArrayOutputStream

Gagravarr
  • 47,320
  • 10
  • 111
  • 156