gpt4 book ai didi

java - 读取 XLSX 工作簿时 Apache POI 抛出 IOException

转载 作者:行者123 更新时间:2023-12-01 07:11:07 25 4
gpt4 key购买 nike

我尝试运行以下代码,但收到 IOException:

String cellText = null;
InputStream is = null;
try {
// Find /mydata/myworkbook.xlsx
is = new FileInputStream("/mydata/myworkbook.xlsx");
is.close();

System.out.println("Found the file!");

// Read it in as a workbook and then obtain the "widgets" sheet.
Workbook wb = new XSSFWorkbook(is);
Sheet sheet = wb.getSheet("widgets");

System.out.println("Obtained the widgets sheet!");

// Grab the 2nd row in the sheet (that contains the data we want).
Row row = sheet.getRow(1);

// Grab the 7th cell/col in the row (containing the Plot 500 English Description).
Cell cell = row.getCell(6);
cellText = cell.getStringCellValue();

System.out.println("Cell text is: " + cellText);
} catch(Throwable throwable) {
System.err.println(throwable.getMessage());
} finally {
if(is != null) {
try {
is.close();
} catch(IOException ioexc) {
ioexc.printStackTrace();
}
}
}

在 Eclipse 中运行它的输出是:

Found the file!
Stream Closed
java.io.IOException: Stream Closed
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:236)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at java.io.PushbackInputStream.read(PushbackInputStream.java:186)
at java.util.zip.ZipInputStream.readFully(ZipInputStream.java:414)
at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:247)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:91)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:51)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:83)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:267)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:204)
at me.myorg.MyAppRunner.run(MyAppRunner.java:39)
at me.myorg.MyAppRunner.main(MyAppRunner.java:25)

异常来自以下行:

Workbook wb = new XSSFWorkbook(is);

根据XSSFWorkbook Java Docs这是 XSSFWorkbook 对象的有效构造函数,我没有看到任何“跳出”的东西来表明我错误地使用了我的 InputStream。任何 POI 专家都可以帮助我找出问题所在吗?提前致谢。

最佳答案

问题很简单:

is = new FileInputStream("/mydata/myworkbook.xlsx");
is.close();

您在将输出流传递给构造函数之前关闭了输出流,并且无法读取它。

只需删除这里的 is.close() 即可解决问题,因为它会在最后的finally语句中被清除。

关于java - 读取 XLSX 工作簿时 Apache POI 抛出 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14070340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com