问题描述
我收到此错误:
我读了Google,发现我需要使用XSSF而不是HSSF,因为我的Excel文件是xlsx,但正如你在我的maven中看到的,我已经在使用xlsx。我在哪里出错了?
I read throw Google and I found out that I need to use XSSF instead of HSSF because my Excel file is xlsx, but as you see in my maven, I am already using xlsx. Where have I gone wrong please?
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13-beta1</version>
</dependency>
这个异常的代码是:
POIFSFileSystem fs;
fs = new POIFSFileSystem(new FileInputStream(getFilePath()));
我的新代码
My new code
public void getBColum() {
try {
OPCPackage fs;
fs = new OPCPackage.open(new File(getFilePath()));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheet("Master column name - Used Car");
XSSFRow row;
CellReference cr = new CellReference("A1");
row = sheet.getRow(cr.getCol());
System.out.println(row.getCell(3));
} catch (FileNotFoundException e) {
if (logger.isDebugEnabled()) {
logger.debug("How can this error be possible? we should have already thrown an exception in the construction");
}
} catch (IOException e) {
logger.error(String.format("Exception in reading the file: %s",
e.getMessage()));
}
}
我有一个编译错误新的oPCPackage.open
它是:
I have a compile error in new oPCPackage.open
which is:
推荐答案
根据, POIFSFileSystem
(或类似地, NPOIFSFileSystem
)仅用于.xls(Excel版本到2003年)文档。
According to the Apache POI Quick Guide, the POIFSFileSystem
(or similarly, NPOIFSFileSystem
) is only used with .xls (Excel versions through 2003) documents.
.xlsx文档(Excel 2007+)的等价物为 OPCPackage
。
The equivalent for .xlsx documents (Excel 2007+) is OPCPackage
.
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
您可以从 XSSFWorkbook
code> OPCPackage :
You can create an XSSFWorkbook
from the OPCPackage
:
XSSFWorkbook wb = new XSSFWorkbook(pkg);
或者你可以直接创建它:
Or you can just create it directly:
XSSFWorkbook wb = new XSSFWorkbook(new File("file.xlsx"));
一般来说,使用文件
而不是 InputStream
,以节省内存。
Generally it's better to create the workbook using a File
instead of an InputStream
, to save memory.
另外,如果你想要的代码不在乎无论是.xls还是.xlsx:
Also, if you want code that doesn't care whether it's an .xls or an .xlsx:
// or "file.xlsx"
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
这篇关于Java POI提供的数据似乎在Office 2007+ XML中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!