如何使用Apache POI或JExcelAPI库的API读取Excel文件
要使用Apache POI或JExcelAPI库的API读取Excel文件,首先需要在项目中添加相应的依赖。
使用Apache POI库:
Maven依赖:
<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样例:假设Excel文件中有一个名为"Sheet1"的工作表,包含姓名和年龄两列数据。
| 姓名 | 年龄 |
|------|------|
| 张三 | 20 |
| 李四 | 25 |
| 王五 | 30 |
Java样例代码:
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 {
// 打开Excel文件
InputStream inputStream = new FileInputStream(new File("path/to/excel_file.xlsx"));
Workbook workbook = new XSSFWorkbook(inputStream);
// 获取工作表
Sheet sheet = workbook.getSheet("Sheet1");
// 遍历行
for (Row row : sheet) {
// 读取单元格数据
Cell cell1 = row.getCell(0);
String name = cell1.getStringCellValue();
Cell cell2 = row.getCell(1);
double age = cell2.getNumericCellValue();
// 打印数据
System.out.println("姓名: " + name + ", 年龄: " + (int)age);
}
// 关闭流
inputStream.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用JExcelAPI库:
Maven依赖:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Excel样例和Java样例代码与Apache POI库的使用方式相同。只需将导入的类名称和部分API调用方式更改为JExcelAPI对应的类和方法。