在内存中写入XSSFWorkbook到内存zip

时间:2014-05-12 09:00:48

标签: java excel zip java-io zipfile

我正在读取db记录并在内存中创建XSSFWorksbook。

完成后,我将此工作簿编写为zip输出流。 zip已正确创建,但xlsx文件未生成属性。代替excel,它创建文件夹和文件,如_rel,工作表,sharedStrings,样式和workbook.xml

//Read records from db and create workbook
public static XSSFWorkbook buildReportDocuement(int reportIndex,
    List<Object> result) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet excelSheet = workbook.createSheet(REPORT_NAME_PREFIX);
    setExcelHeader(excelSheet);
    processActivityReportData(result, excelSheet);      
    return workbook;
}

//reading worksbooks into bytearray and addign to in memory zip files
public static ByteArrayOutputStream zipWorkbooks(
    List<XSSFWorkbook> workbooks) throws IOException {

    int workBookIndex = 1;
    ByteArrayOutputStream byteOutputStream = null;
    FileOutputStream outputStream = new FileOutputStream("Reports");
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    ZipEntry zipEntry = null;

    for (XSSFWorkbook current : workbooks) {
        zipEntry = new ZipEntry(REPORT_PREFIX + workBookIndex
            + EXCEL_EXTENSION);
        zipOutputStream.putNextEntry(zipEntry);
        byteOutputStream = new ByteArrayOutputStream();
        current.write(byteOutputStream);
        if (byteOutputStream != null) {
            zipEntry.setSize(byteOutputStream.size());
            zipOutputStream.write(byteOutputStream.toByteArray());
            zipOutputStream.closeEntry();
        }
    }
    zipOutputStream.close();
    return byteOutputStream;
}

我不应该将任何文件写入文件系统。请指导我。

1 个答案:

答案 0 :(得分:0)

好吧,最后我发现了。问题出在我的逻辑上。我想念了ByteArrayOutputStram的概念。我已经对zipWorkbooks功能进行了更改,它运行得很好。变化是:

public static ByteArrayOutputStream zipWorkbooks(       列表工作簿)抛出IOException {       int workBookIndex = 1;       ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();       ByteArrayOutputStream workbookByteArrayStream = null;
      ZipOutputStream zipOutputStream = new ZipOutputStream(byteOutputStream);       ZipEntry zipEntry = null;

  for (XSSFWorkbook current : workbooks) {
     zipEntry = new ZipEntry(REPORT_PREFIX + workBookIndex
        + EXCEL_EXTENSION);
     zipOutputStream.putNextEntry(zipEntry);
     workbookByteArrayStream = new ByteArrayOutputStream();
     current.write(workbookByteArrayStream);            
     zipEntry.setSize(workbookByteArrayStream.size());
     zipOutputStream.write(workbookByteArrayStream.toByteArray());
     zipOutputStream.closeEntry();          
  }     
  zipOutputStream.close();
  return byteOutputStream;

}