Java 将 Excel 数据导入数据库226
在许多实际项目中,我们需要将 Excel 表格中的数据导入到数据库中以进行存储和分析。本文将介绍使用 Java 编程语言将 Excel 数据导入到关系型数据库(如 MySQL)的步骤和示例代码。
技术栈* Java 8 或更高版本
* Apache POI(用于读取和写入 Excel 文件)
* JDBC(用于连接和操作数据库)
步骤
1. 导入依赖项
在项目中添加以下依赖项:
```xml
poi
5.2.2
mysql
mysql-connector-java
8.0.31
```
2. 读取 Excel 文件
使用 Apache POI 读取 Excel 文件并获取工作表:
```java
FileInputStream fis = new FileInputStream("");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = (0);
```
3. 连接数据库
使用 JDBC 驱动程序连接到数据库并获取连接:
```java
Connection conn = (
"jdbc:mysql://localhost:3306/database",
"user",
"password"
);
```
4. 创建数据库表(可跳过)
如果数据库中不存在目标表,可以创建它:
```java
Statement stmt = ();
("CREATE TABLE IF NOT EXISTS table_name (id INT NOT NULL, name VARCHAR(255), PRIMARY KEY (id))");
```
5. 遍历 Excel 行
遍历 Excel 行并获取单元格值:
```java
for (Row row : sheet) {
int id = (int) (0).getNumericCellValue();
String name = (1).getStringCellValue();
// ...
}
```
6. 准备 SQL 语句
准备用于插入数据的 SQL 语句:
```java
PreparedStatement ps = ("INSERT INTO table_name (id, name) VALUES (?, ?)");
```
7. 绑定参数并执行插入
依次将数据绑定到 SQL 语句的参数,然后执行插入:
```java
for (Row row : sheet) {
int id = (int) (0).getNumericCellValue();
String name = (1).getStringCellValue();
(1, id);
(2, name);
();
}
```
8. 关闭资源
关闭 Excel 工作簿、数据库连接、语句和结果集:
```java
();
();
();
();
```
示例代码```java
import .*;
import ;
import .*;
public class ExcelToDatabase {
public static void main(String[] args) {
try {
// 读取 Excel 文件
FileInputStream fis = new FileInputStream("");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = (0);
// 连接数据库
Connection conn = (
"jdbc:mysql://localhost:3306/database",
"user",
"password"
);
// 创建数据库表(可跳过)
Statement stmt = ();
("CREATE TABLE IF NOT EXISTS table_name (id INT NOT NULL, name VARCHAR(255), PRIMARY KEY (id))");
// 准备 SQL 语句
PreparedStatement ps = ("INSERT INTO table_name (id, name) VALUES (?, ?)");
// 遍历 Excel 行
for (Row row : sheet) {
int id = (int) (0).getNumericCellValue();
String name = (1).getStringCellValue();
// 绑定参数并执行插入
(1, id);
(2, name);
();
}
// 关闭资源
();
();
();
();
("数据已成功导入到数据库");
} catch (Exception e) {
();
}
}
}
```
注意事项* 如果 Excel 文件中有空单元格,则需要进行相应的空值处理。
* 根据实际情况调整 SQL 语句和数据类型。
* 确保数据库表结构与 Excel 数据格式一致。
* 使用事务处理机制保证数据完整性。
2024-12-01
上一篇:Java 中的数据类型赋值
下一篇:Java对象数组转换为JSON
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html