java实现excel导入数据库
时间: 2023-11-18 13:58:54 浏览: 49
可以使用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 ExcelToDatabase {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/test_db";
String username = "root";
String password = "password";
String excelFilePath = "path/to/excel/file.xlsx";
try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
String sql = "INSERT INTO employees (id, name, age) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
FileInputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Cell idCell = row.getCell(0);
Cell nameCell = row.getCell(1);
Cell ageCell = row.getCell(2);
int id = (int) idCell.getNumericCellValue();
String name = nameCell.getStringCellValue();
int age = (int) ageCell.getNumericCellValue();
statement.setInt(1, id);
statement.setString(2, name);
statement.setInt(3, age);
statement.executeUpdate();
}
workbook.close();
inputStream.close();
System.out.println("Data imported successfully!");
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例代码中,我们首先定义了数据库连接的URL、用户名和密码。然后,我们指定了Excel文件的路径,并使用FileInputStream读取Excel文件。接下来,我们使用XSSFWorkbook类来创建一个Workbook对象,并获取第一个工作表。然后,我们使用for循环遍历每一行,并从每个单元格中获取数据。最后,我们将数据插入到数据库中。
请注意,这只是一个简单的示例代码,实际应用中可能需要更多的错误处理和数据验证。