5i需要将HSSFWorkbook(Apache的POI)转换为ByteArray,然后将ByteArray转换回HSSFWorkbook。以下TestCase说明了我的问题:
@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);
}
}
testcase失败,异常:java.io.IOException:标头签名无效;读取0x0005060000100809,预期为0xE11AB1A1E011CFD0
(我正在使用Apaches POI 3.5-beta3)
我希望有人可以帮助我...我怎样才能让它发挥作用?!
答案 0 :(得分:2)
您没有正确编写工作簿!您需要使用write(Outputstream)来电。
如various examples on the website所示,您的代码应改为:
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()));
另外,如果您直接使用File,请不要从FileInputStream打开工作簿。从文件uses less memory than from a Stream开始。