从 HSSFWorkbook 生成 xls 文件

Generate xls-file from HSSFWorkbook

我正在创建一个 excel 文件:

public byte[] createReport() {
    List<ExportModel> exportModels = export.computeExportModels();
    HSSFWorkbook workbook = excelCreator.createWorkbook(exportModels);

    // return workbook.getBytes();
    return getByteArray(workbook);
}

private byte[] getByteArray(HSSFWorkbook workbook) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        workbook.write(bos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return bos.toByteArray();
}

虽然这确实有效,但不适用于

workbook.getBytes();

如果我尝试打开生成的 xls 文件,Excel 会崩溃并且无法打开它。你有这方面的经验吗?

来自Apache POI javadocs for HSSFWorkbook.getBytes()

public byte[] getBytes()

Method getBytes - get the bytes of just the HSSF portions of the XLS file. Use this to construct a POI POIFSFileSystem yourself.

Excel .xls 文件 必须 包装在外部 OLE2 容器中,例如由 POIFSFileSystem 生成。因此,您要么需要自己完成所有操作,要么只需调用 HSSFWorkbook.write(OutputStream) which does it all for you (as the javadocs explain)

如果你想写一个 HSSFWorkbook 并获取它的字节,那么除非你想做一些非常特别的事情,否则就这样做:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
bytes[] excelFile = baos.toByteArray();