使用java在內存中創建excel文件並傳遞為字節以供下載

[英]creating an excel file in memory using java and pass as bytes for downloading


I have created a excel file using jxl library. The code is working fine but the only problem is that each time for building an excel file from the dynamic values coming from a service, the excel content is overwriting onto a test.xls like as shown below. Is there any way to build an excel in memory and pass the byte for downloading it instead of creating an external file ("test.xls")

我使用jxl庫創建了一個excel文件。代碼工作正常,但唯一的問題是,每次從服務的動態值構建excel文件時,excel內容都會覆蓋到test.xls上,如下所示。有沒有辦法在內存中構建一個excel並傳遞該字節以便下載它而不是創建一個外部文件(“test.xls”)

File file = new File("test.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
:
:
:
:

InputStream in = new FileInputStream(file);

if (in == null) {
    out.close();
}
else 
{
    byte[] buffer = new byte[4096];
    int len;

    while ((len = in.read(buffer)) != -1) {
        out.write(buffer, 0, len);
    }

    out.flush();
    in.close();
    out.close();
}

Can anyone please help me on this

任何人都可以請幫助我

2 个解决方案

#1


3  

Use a ByteArrayOutputStream in combination with the Workbook.createWorkbook(OutputStream os) method to create the workbook in memory, and dump the created byte array to whatever output stream you want.

將ByteArrayOutputStream與Workbook.createWorkbook(OutputStream os)方法結合使用可在內存中創建工作簿,並將創建的字節數組轉儲到所需的任何輸出流。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableWorkbook workbook = Workbook.createWorkbook(baos);

// ...

workbook.close();
out.write(baos.toByteArray());
out.flush();
out.close();

Alternatively, you could do it on the fly, without using the intermediate byte array:

或者,您可以在不使用中間字節數組的情況下即時執行此操作:

WritableWorkbook workbook = Workbook.createWorkbook(out);

// ...

workbook.close();
out.flush();
out.close();

This method may be preferable as JXL is keeping the workbook in memory anyway, and only flushes it to he output stream when the workbook is closed.

此方法可能是優選的,因為JXL無論如何都將工作簿保留在內存中,並且僅在工作簿關閉時將其刷新到輸出流。

#2


0  

Here is example to create excel using POI and converting it to bytes.

下面是使用POI創建excel並將其轉換為字節的示例。

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Sheet 1");

    Row row = sheet.createRow(1);
    Cell cell = row.createCell(cellnum++);
    cell.setCellValue((String) obj);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        workbook.write(bos);
    } catch (IOException e) {
    } finally {
        try {
            bos.close();
            workbook.close();
        } catch (IOException e) {
        }
    }
    byte[] bytes = bos.toByteArray();

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/10/26/72f159908e6e30dd2e8ef6941b52132f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com