java 从上传的 .xlsx(2007 Excel 文件)创建 xssf 工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9934481/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:57:04  来源:igfitidea点击:

Creating an xssf workbook from an uploaded .xlsx(2007 Excel file)

javaapache-poi

提问by Abhay

In the code the client uploads a standard .xlsx file through struts.

在代码中,客户端通过struts 上传一个标准的.xlsx 文件。

In the action we take the file using

在操作中,我们使用文件

FormFile myfile = ABCForm.getTheFile();

My query is how would I create a XSSFWorkbook out of this file.

我的查询是如何从这个文件中创建一个 XSSFWorkbook。

I also have a parallel process for accessing 2003 excel file this way

我也有通过这种方式访问​​ 2003 excel 文件的并行过程

FormFile myfile = ABCForm.getTheFile();
byte[] fileData = myFile.getFileData();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);

in the Helper class

POIFSFileSystem fs = new POIFSFileSystem(byteArrayInputStream);
HSSFWorkbook wb = new HSSFWorkbook(fs);

and then further processing of the workbook.

然后进一步处理工作簿。

I would like to know how to create a XSSFWorkbook as I have created the HSSFWorkbook above.

我想知道如何创建 XSSFWorkbook,因为我在上面创建了 HSSFWorkbook。

I have all the ooxml and related jars in the classpath and lib folder.

我在 classpath 和 lib 文件夹中有所有 ooxml 和相关的 jars。

XSSFWorkbook cannot be created from byteArrayInputStream. Apache XSSF Workbook. It can only be created from Inputstream and OPCPackage.

无法从 byteArrayInputStream 创建 XSSFWorkbook。Apache XSSF 工作簿。它只能从 Inputstream 和 OPCPackage 创建。

Any ideas/pointers on how to go about further. I will be glad to give further details about any other code snippets that would help.

关于如何进一步进行的任何想法/指示。我很乐意提供有关任何其他有帮助的代码片段的更多详细信息。

回答by Gagravarr

You can happily create a XSSFWorkbook from an InputStream

你可以愉快地从 InputStream 创建一个 XSSFWorkbook

One option is to use WorkbookFactory, which auto-detects the appropriate type and returns a HSSFWorkbook or XSSFWorkbook for you:

一种选择是使用 WorkbookFactory,它会自动检测适当的类型并为您返回 HSSFWorkbook 或 XSSFWorkbook:

Workbook wb = WorkbookFactory.create(inputStream);

Otherwise, you can create a XSSFWorkbook from a stream like this:

否则,您可以从这样的流创建 XSSFWorkbook:

XSSFWorkbook wb = new XSSFWorkbook(OPCPackage.open(inputStream));

However, be aware that opening a XSSFWorkbook from a File needs less memory than from a Stream - with a Stream the whole file will need to be buffered into memory

但是,请注意,从文件中打开 XSSFWorkbook 所需的内存比从 Stream 中少 - 使用 Stream 时,整个文件将需要缓冲到内存中