用Java怎么把Excel表格里的数据写入到mysql数据库表中
时间: 2024-04-14 07:30:30 浏览: 281
您可以使用 Apache POI 库来读取 Excel 表格中的数据,并使用 JDBC 连接 MySQL 数据库并将数据写入表中。
以下是一个示例代码:
```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 ExcelToMySQL {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database_name";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD)) {
String excelFilePath = "path_to_your_excel_file.xlsx";
FileInputStream fileInputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
// Assuming the first column contains the data you want to insert into the database
Cell cell = row.getCell(0);
String data = cell.getStringCellValue();
String sql = "INSERT INTO your_table_name (column_name) VALUES (?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, data);
statement.executeUpdate();
}
workbook.close();
fileInputStream.close();
System.out.println("Data inserted successfully into MySQL database.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请确保您已经将 `your_database_name` 替换为实际的数据库名,`your_username` 和 `your_password` 替换为数据库的用户名和密码,`path_to_your_excel_file.xlsx` 替换为实际的 Excel 文件路径,`your_table_name` 替换为要插入数据的表名,`column_name` 替换为要插入数据的列名。
这段代码将逐行读取 Excel 表格中的数据,并将其插入到 MySQL 数据库表中。请根据您的实际需求进行适当修改。
阅读全文