How to use the API of Apache POI or JExcel API library to read Excel files
To use the API of the Apache POI or JExcel API library to read Excel files, you first need to add the corresponding dependencies in the project.
Using the Apache POI library:
Maven Dependency:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
Excel example: Suppose there is a worksheet named "Sheet1" in the Excel file, which contains two columns of data: name and age.
|Name | Age|
|------|------|
|Zhang San | 20|
|Li Si | 25|
|Wang Wu | 30|
Java sample code:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadExcelWithPOI {
public static void main(String[] args) {
try {
//Open Excel file
InputStream inputStream = new FileInputStream(new File("path/to/excel_file.xlsx"));
Workbook workbook = new XSSFWorkbook(inputStream);
//Get Worksheet
Sheet sheet = workbook.getSheet("Sheet1");
//Traversal row
for (Row row : sheet) {
//Read Cell Data
Cell cell1 = row.getCell(0);
String name = cell1.getStringCellValue();
Cell cell2 = row.getCell(1);
double age = cell2.getNumericCellValue();
//Print Data
System. out. println ("Name:"+name+", Age:"+(int) age);
}
//Close Stream
inputStream.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using the JExcelAPI library:
Maven Dependency:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
The Excel sample and Java sample code are used in the same way as the Apache POI library. Simply change the imported class name and some API call methods to the corresponding classes and methods of the JExcel API.