java实现excel导入mysql
时间: 2023-04-25 19:03:59 浏览: 158
Java将excel中的数据导入到mysql中
Java可以使用Apache POI库来读取Excel文件,然后将数据插入到MySQL数据库中。
具体步骤如下:
1. 导入Apache POI和MySQL JDBC驱动包。
2. 使用POI库读取Excel文件,获取数据。
3. 连接MySQL数据库,创建表格。
4. 将Excel数据插入到MySQL表格中。
5. 关闭连接,释放资源。
示例代码:
```
import java.io.File;
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.ss.usermodel.WorkbookFactory;
public class ExcelToMysql {
public static void main(String[] args) {
String excelFilePath = "path/to/excel/file.xlsx";
String mysqlUrl = "jdbc:mysql://localhost:3306/test";
String mysqlUser = "root";
String mysqlPassword = "password";
String tableName = "students";
try {
// 读取Excel文件
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt();
// 连接MySQL数据库
Connection connection = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
// 创建表格
String createTableSql = "CREATE TABLE IF NOT EXISTS " + tableName + " (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), age INT)";
PreparedStatement createTableStatement = connection.prepareStatement(createTableSql);
createTableStatement.execute();
// 插入数据
String insertSql = "INSERT INTO " + tableName + " (name, age) VALUES (?, ?)";
PreparedStatement insertStatement = connection.prepareStatement(insertSql);
for (Row row : sheet) {
Cell nameCell = row.getCell();
Cell ageCell = row.getCell(1);
String name = nameCell.getStringCellValue();
int age = (int) ageCell.getNumericCellValue();
insertStatement.setString(1, name);
insertStatement.setInt(2, age);
insertStatement.executeUpdate();
}
// 关闭连接
insertStatement.close();
createTableStatement.close();
connection.close();
workbook.close();
inputStream.close();
System.out.println("导入成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文