在 Java 中实现 Excel 导入功能有多种方式,以下是几种常见的实现方式,每种方式都包含了步骤流程、依赖坐标和示例代码。
注意: 为了演示,我会使用 Apache POI 作为 Excel 处理库。在实际项目中,你可以根据需要选择其他库,如 JExcelAPI、EasyExcel 等。
步骤流程:
Maven 依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
Gradle 依赖:
implementation 'org.apache.poi:poi:5.0.0'
implementation 'org.apache.poi:poi-ooxml:5.0.0'
示例代码:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.InputStream;
public class ExcelImportUsingPOI {
public static void main(String[] args) {
String excelFilePath = "path/to/your/excel/file.xlsx";
try (InputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(inputStream)) {
Sheet sheet = workbook.getSheetAt(0); // Assuming you're working with the first sheet
for (Row row : sheet) {
for (Cell cell : row) {
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
System.out.print(cell.getStringCellValue() + "\t");
} else if (cellType == CellType.NUMERIC) {
System.out.print(cell.getNumericCellValue() + "\t");
} // Handle other cell types as needed
}
System.out.println(); // Move to the next row
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
步骤流程:
Maven 依赖:
<dependency>
<groupId>com.alibaba.easyexcel</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.1</version>
</dependency>
Gradle 依赖:
implementation 'com.alibaba.easyexcel:easyexcel:3.0.1'
示例代码:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.Map;
public class ExcelImportUsingEasyExcel {
public static void main(String[] args) {
String excelFilePath = "path/to/your/excel/file.xlsx";
EasyExcel.read(excelFilePath, new ExcelListener()).sheet().doRead();
}
static class ExcelListener extends AnalysisEventListener<Map<Integer, String>> {
@Override
public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
rowData.forEach((index, value) -> {
System.out.print(value + "\t");
});
System.out.println(); // Move to the next row
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// All rows have been read
}
}
}
这里介绍了两种常见的 Java Excel 导入方式,分别使用了 Apache POI 和 EasyExcel。根据你的需求和项目要求,选择其中一种方式进行实现即可。请注意根据示例代码进行适当的调整和定制。