在 Java 中导入 Excel 数据有多种实现方式,其中常用的包括 Apache POI、JExcelApi 和 EasyExcel。下面我会详细介绍这三种方式的步骤流程,包括 Maven 和 Gradle 的依赖坐标,以及示例代码。
Maven:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
Gradle:
implementation 'org.apache.poi:poi:5.0.0'
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class ApachePOIExample {
public static void main(String[] args) {
try (InputStream inputStream = new FileInputStream("example.xlsx")) {
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0); // Assuming the first sheet
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = cell.getStringCellValue();
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Gradle:
implementation 'net.sourceforge.jexcelapi:jxl:2.6.12'
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import java.io.File;
public class JExcelApiExample {
public static void main(String[] args) {
try {
File file = new File("example.xls");
Workbook workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet(0); // Assuming the first sheet
for (int row = 0; row < sheet.getRows(); row++) {
for (int col = 0; col < sheet.getColumns(); col++) {
Cell cell = sheet.getCell(col, row);
String cellValue = cell.getContents();
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.0-beta6</version>
</dependency>
Gradle:
implementation 'com.alibaba:easyexcel:3.0.0-beta6'
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class EasyExcelExample {
public static void main(String[] args) {
String filePath = "example.xlsx";
EasyExcel.read(filePath, new ExcelListener()).sheet().doRead();
}
static class ExcelListener extends AnalysisEventListener<List<String>> {
private List<List<String>> dataList = new ArrayList<>();
@Override
public void invoke(List<String> rowData, AnalysisContext context) {
dataList.add(rowData);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
for (List<String> row : dataList) {
for (String cellValue : row) {
System.out.print(cellValue + "\t");
}
System.out.println();
}
}
}
}
这些是导入 Excel 数据的三种常用实现方式,你可以根据需求选择其中一种适合的方法。每种方法都有其特点和优劣势,具体选择取决于项目需求和个人偏好。