Java – Cannot write HSSFWorkbook to ByteArray and then read it to HSSFWorkbook

apache-poibytearrayjavastream

5i need to convert a HSSFWorkbook (Apache's POI) to an ByteArray and later to convert the ByteArray back to the HSSFWorkbook. The following TestCase illustrates my problem:

   @Test
   public void testXLSExportImport(){
      try {
         InputStream is = new FileInputStream(FILEPATH);
         HSSFWorkbook wb = new HSSFWorkbook(is);
         byte[] exported = wb.getBytes();
         HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(exported)); 
         //in the line above the exception is thrown
      } catch (Exception e) {
         assertTrue(false);
      }
   }

the testcase fails with the exception: java.io.IOException: Invalid header signature; read 0x0005060000100809, expected 0xE11AB1A1E011CFD0

(I am using Apaches POI 3.5-beta3)

I hope somebody can help me… how can I get it work?!

Best Answer

You're not writing the workbook correctly! You need to use the write(Outputstream) call.

As shown in the various examples on the website, your code should instead be:

     InputStream is = new FileInputStream(FILEPATH);
     HSSFWorkbook wb = new HSSFWorkbook(is);
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     wb.write(out);
     HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); 

Also, don't open a Workbook from a FileInputStream, if you have a File use that directly. Opening from a File uses less memory than from a Stream.