java如何读取excel数据
读取Excel数据的常用方法
在Java中读取Excel数据可以通过多种方式实现,以下是几种常见的方法和对应的工具库。
使用Apache POI库
Apache POI是处理Microsoft Office文档的流行Java库,支持读取和写入Excel文件(.xls和.xlsx格式)。
添加依赖(Maven)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
读取Excel文件

import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
public class ReadExcel {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("example.xlsx");
Workbook workbook = WorkbookFactory.create(fis)) {
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
default:
System.out.print("[UNKNOWN]\t");
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用EasyExcel库
EasyExcel是阿里巴巴开源的一个简单高效的Excel处理工具,特别适合大数据量的读取。
添加依赖(Maven)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
读取Excel文件

import com.alibaba.excel.EasyExcel;
import java.util.List;
public class ReadExcel {
public static void main(String[] args) {
String fileName = "example.xlsx";
EasyExcel.read(fileName, new ExcelDataListener()).sheet().doRead();
}
}
// 自定义监听器
class ExcelDataListener implements AnalysisEventListener<Object> {
@Override
public void invoke(Object data, AnalysisContext context) {
System.out.println(data); // 逐行处理数据
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("读取完成");
}
}
使用JExcelAPI(JXL)库
JExcelAPI是一个较老的库,仅支持.xls格式的Excel文件。
添加依赖(Maven)
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
读取Excel文件
import jxl.*;
import java.io.File;
public class ReadExcel {
public static void main(String[] args) {
try {
Workbook workbook = Workbook.getWorkbook(new File("example.xls"));
Sheet sheet = workbook.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
System.out.print(cell.getContents() + "\t");
}
System.out.println();
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法对比
- Apache POI:功能强大,支持.xls和.xlsx格式,适合复杂场景。
- EasyExcel:适合大数据量读取,内存占用低,使用简单。
- JExcelAPI:仅支持.xls格式,适合老旧项目。
根据需求选择合适的工具库,大多数现代项目推荐使用Apache POI或EasyExcel。






