I'm reading excel using Apache POI but it keeps giving error for XSSFWorkbook class definition found error. I used different versions of Apache-poi jar libraries (i.e 4.1 , 4.0 and 3.12) none of them seem to fix this error. Here's a screenshot of libraries currently imported enter image description here Whats wrong inside the code ?
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;
}
Error shown:
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)
You have to include poi jar file. It's version will be 4.1.0. If you are using Maven pom.xml, include the following dependency.
<!-- 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>
If you are not using Maven, download the jar files from the following locations.
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
For reading an excel file with Apache POI, you need the following jar files if you do not want to use Maven.
- poi-ooxml-4.1.0.jar
- poi-ooxml-schemas-4.1.0.jar
- xmlbeans-3.1.0.jar
- commons-compress-1.18.jar
- curvesapi-1.06.jar
- poi-4.1.0.jar
- commons-codec-1.12.jar
- commons-collections4-4.3.jar
- commons-math3-3.6.1.jar
I provide below a brief code snippet about how to use.
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());
}