Java 从 Apache 的 POI 工作簿获取 InputStream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21156461/
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
Get InputStream from Apache's POI Workbook
提问by ioreskovic
Is there a way to obtain InputStream
of Apache's POI Workbook?
有没有办法获得InputStream
Apache 的 POI 工作簿?
I need it for piping to another OutputStream
, however I'm unable to find such method (If it exists).
我需要它来管道到另一个OutputStream
,但是我无法找到这样的方法(如果存在)。
If it doesn't, any tips on alternative ways to obtain it?
如果没有,有关获取它的其他方法的任何提示?
采纳答案by Alexander Tokarev
There's a several ways to solve this:
有几种方法可以解决这个问题:
- You can use standard java
PipetInputStream
andPipedOutputStream
. But you have to create different thread for usingPipedInputStream
(as described in http://docs.oracle.com/javase/7/docs/api/java/io/PipedInputStream.html) - You can write the content to
ByteArrayOutputStream
, and then you can use resulting byte array viaByteArrayInputStream
. This can be done sequentially in one thread.
- 您可以使用标准的 java
PipetInputStream
和PipedOutputStream
. 但是您必须创建不同的线程以供使用PipedInputStream
(如http://docs.oracle.com/javase/7/docs/api/java/io/PipedInputStream.html 中所述) - 您可以将内容写入
ByteArrayOutputStream
,然后您可以通过 使用生成的字节数组ByteArrayInputStream
。这可以在一个线程中按顺序完成。
回答by Vinit Kumarq
You can check https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java
here they are converting the whole sheet to csv file, using inputstream which they got from XLSX file.
在这里,他们使用从 XLSX 文件获得的输入流将整个工作表转换为 csv 文件。
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
int index = 0;
while (iter.hasNext()) {
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
this.output.println();
this.output.println(sheetName + " [index=" + index + "]:");
processSheet(styles, strings, new SheetToCSV(), stream);
stream.close();
++index;
}
回答by Kehinde Adedamola Shittu
Here's how to implement #2 of Alexander Tokarev's answer (i.e get Inputstream from a workbook):
以下是如何实现 Alexander Tokarev 答案的#2(即从工作簿获取 Inputstream):
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] barray = bos.toByteArray();
InputStream is = new ByteArrayInputStream(barray);
} catch (IOException e) {
e.printStackTrace();
}
回答by LottaLava
You can extend XSSFWorkbook, save the File or InputStream object from constructor and them get it back with some method like getInputStream()
您可以扩展 XSSFWorkbook,从构造函数中保存 File 或 InputStream 对象,然后他们使用诸如 getInputStream() 之类的方法将其取回