用Java将本地的excel表格放到mysql上
时间: 2024-04-29 17:24:30 浏览: 11
1. 首先需要安装mysql数据库和Java编程环境。
2. 在Java中使用Apache POI库读取本地的excel表格数据。
3. 使用JDBC连接mysql数据库并创建表格。
4. 将excel表格数据插入到mysql表格中。
以下是示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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 {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/testdb"; // mysql数据库连接url
String username = "root"; // 数据库用户名
String password = "123456"; // 数据库密码
String excelFilePath = "path/to/excel/file.xlsx"; // excel文件路径
try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password)) {
String createTableSql = "CREATE TABLE IF NOT EXISTS employee (\n"
+ " id INT PRIMARY KEY,\n"
+ " name VARCHAR(50),\n"
+ " age INT,\n"
+ " salary FLOAT\n"
+ ");"; // 创建mysql表格的sql语句
try (PreparedStatement createTableStmt = conn.prepareStatement(createTableSql)) {
createTableStmt.execute();
}
try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath))) {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0); // 获取第一个sheet
for (Row row : sheet) {
int id = (int) row.getCell(0).getNumericCellValue();
String name = row.getCell(1).getStringCellValue();
int age = (int) row.getCell(2).getNumericCellValue();
float salary = (float) row.getCell(3).getNumericCellValue();
String insertSql = "INSERT INTO employee (id, name, age, salary) VALUES (?, ?, ?, ?);"; // 插入mysql表格的sql语句
try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
insertStmt.setInt(1, id);
insertStmt.setString(2, name);
insertStmt.setInt(3, age);
insertStmt.setFloat(4, salary);
insertStmt.executeUpdate();
}
}
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们使用了Apache POI库读取excel表格数据,并使用JDBC连接mysql数据库并创建表格。然后,我们将excel表格数据插入到mysql表格中。运行该代码可以将excel表格中的数据放到mysql上。