java 使用java在内存中创建一个excel文件并作为字节传递以供下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40253515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating an excel file in memory using java and pass as bytes for downloading
提问by Alex Man
I have created a excel file using jxllibrary. 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.xlslike 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
任何人都可以帮我解决这个问题吗
回答by Robby Cornelissen
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.
将 aByteArrayOutputStream
与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 无论如何都将工作簿保存在内存中,并且仅在工作簿关闭时才将其刷新到输出流。
回答by usr_11
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();