Java 怎么导入Excel数据到数据库
时间: 2023-09-15 19:24:39 浏览: 132
你可以使用 Java 的 Apache POI 库来读取 Excel 文件,并使用 JDBC 连接数据库将数据导入到数据库中。下面是一个简单的示例代码:
```java
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelToDatabaseImporter {
public static void main(String[] args) {
String filePath = "path_to_excel_file.xlsx"; // 替换为你的 Excel 文件路径
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password")) {
FileInputStream fileInputStream = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String column1 = "";
String column2 = "";
for (Cell cell : row) {
int columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case 0:
column1 = cell.getStringCellValue();
break;
case 1:
column2 = cell.getStringCellValue();
break;
// 可根据需要继续添加其他列
}
}
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, column1);
statement.setString(2, column2);
// 可根据需要继续设置其他参数
statement.executeUpdate();
}
System.out.println("数据导入完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请将 `path_to_excel_file.xlsx` 替换为你的 Excel 文件的实际路径,`jdbc:mysql://localhost:3306/database_name` 替换为你的数据库连接信息,`username` 和 `password` 替换为数据库的用户名和密码,`table_name` 替换为目标表的名称。你还可以根据需要调整代码以适应你的具体要求。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)