轻松上手:Java高效导入Excel文件全攻略,告别繁琐操作!

引言
在Java开发中,处理Excel文件是一个常见的需求。Apache POI是Java中处理Excel文件的一个强大工具。本文将详细介绍如何使用Apache POI在Java中高效导入Excel文件,包括准备工作、代码实现和注意事项。
准备工作
1. 添加Apache POI依赖
首先,您需要在项目中添加Apache POI的依赖。以下是Maven配置示例:


org.apache.poi
poi-ooxml
5.2.2


2. 理解Excel文件格式
Excel文件主要有两种格式:
.xls
和
.xlsx
。Apache POI支持这两种格式。
.xls
是基于二进制的,而
.xlsx
是基于XML的。
代码实现
1. 读取Excel文件
以下是一个简单的示例,展示如何使用Apache POI读取Excel文件:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream(“path/to/your/excel/file.xlsx”);
Workbook workbook = new XSSFWorkbook(fileInputStream);
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;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + “\t”);
break;
default:
System.out.print(“Unknown\t”);
}
}
System.out.println();
}
}
}
2. 导入Excel数据到数据库
以下是一个示例,展示如何将Excel数据导入到数据库中:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ExcelToDatabase {
public static void main(String[] args) throws IOException, SQLException {
FileInputStream fileInputStream = new FileInputStream(“path/to/your/excel/file.xlsx”);
Workbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0);

Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/your_database”, “username”, “password”);
PreparedStatement preparedStatement = connection.prepareStatement(“INSERT INTO your_table (column1, column2) VALUES (?, ?)”);

for (Row row : sheet) {
String column1 = row.getCell(0).getStringCellValue();
String column2 = row.getCell(1).getStringCellValue();
preparedStatement.setString(1, column1);
preparedStatement.setString(2, column2);
preparedStatement.executeUpdate();
}

preparedStatement.close();
connection.close();
}
}
注意事项
处理异常
:在读取和写入Excel文件时,请务必处理可能发生的异常,例如
IOException
和
SQLException
。
性能优化
:当处理大量数据时,考虑使用流式API来提高性能。
安全性
:确保您处理的Excel文件来自可信的来源,以避免潜在的安全风险。
通过以上步骤,您可以在Java中高效地导入Excel文件,并实现数据分析和处理。祝您在Java开发中一切顺利!