java - 无法使用 Apache POI 读取 Excel
问题描述
我正在使用 Apache POI 阅读 excel,但它一直为 XSSFWorkbook 类定义发现错误给出错误。我使用了不同版本的 Apache-poi jar 库(即 4.1、4.0 和 3.12),它们似乎都没有修复这个错误。这是当前导入的库的屏幕截图 在 此处输入图像描述 代码中有什么问题?
try {
File fileSrc = new File("C://Eclipse-Workspace//TestData//TestDataSet.xlsx");
FileInputStream fis = new FileInputStream(fileSrc);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFCell cellData = sheet.getRow(rowNo).getCell(colNo);
workbook.close();
return cellData.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
显示错误:
java.lang.NoClassDefFoundError:
org/apache/poi/ss/usermodel/WorkbookFactory
at Utilities.DataAccessorExcel.excelReader(DataAccessorExcel.java:33)
at TestCases.LoginTest.verifyLogin(LoginTest.java:66)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
atjava.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMe
thodAccessorImpl.java:62)
atjava.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Dele
gatingMethodAccessorImpl.java:43)at
java.base/java.lang.reflect.Method.invoke(Method.java:567)
解决方案
您必须包含 poi jar 文件。它的版本将是 4.1.0。如果您使用的是 Maven pom.xml,请包含以下依赖项。
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
如果您不使用 Maven,请从以下位置下载 jar 文件。
http://central.maven.org/maven2/org/apache/poi/poi/4.1.0/poi-4.1.0.jar
http://central.maven.org/maven2/org/apache/poi/poi-ooxml/4.1.0/poi-ooxml-4.1.0.jar
要使用 Apache POI 读取 excel 文件,如果您不想使用 Maven,则需要以下 jar 文件。
- poi-ooxml-4.1.0.jar
- poi-ooxml-schemas-4.1.0.jar
- xmlbeans-3.1.0.jar
- commons-compress-1.18.jar
- 曲线API-1.06.jar
- poi-4.1.0.jar
- commons-codec-1.12.jar
- commons-collections4-4.3.jar
- commons-math3-3.6.1.jar
我在下面提供了一个关于如何使用的简短代码片段。
FileInputStream file =
new FileInputStream(
new File(
"testdata\\TestData_01.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Cell cell0 = row.getCell(0);
if (cell0 != null) {
System.out.println("First Column Data : "+cell0.getStringCellValue());
}
Cell cell1 = row.getCell(1);
if (cell1 != null) System.out.println("Second Column Data : "+cell1.getStringCellValue());
}
推荐阅读
- php - 为什么我不能在 MongoDB 文档中存储关联数组?
- python - 深入 dirs\sub-dirs 查找特定文件名
- node.js - 使用 Cheerio 获取 XML 文档中的所有标签
- xquery - 如何计算具有两个“限制”的元素?
- xml - 如何获取 xml 文件中特定值的值?
- node.js - 许多有序队列 - 如何在应用程序实例之间自动重新平衡流?
- c++ - 为什么我的类对象会导致未声明的标识符错误?
- sml - 在 Trie 中插入值
- python - 使用 argparse 解析多个相同的参数组
- kubernetes - 如果它依赖于另一个服务端点,如何创建 Kubernetes 端点