java代码 将excel导入mysql
时间: 2023-11-05 21:09:39 浏览: 103
Java将excel中的数据导入到mysql中
以下是将Excel表格导入MySQL数据库的Java代码示例:
```java
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 java.util.Iterator;
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 url = "jdbc:mysql://localhost:3306/test"; //数据库URL
String username = "root"; //数据库用户名
String password = "123456"; //数据库密码
String driverName = "com.mysql.jdbc.Driver"; //JDBC驱动名
Connection conn = null;
PreparedStatement ps = null;
try {
//加载JDBC驱动
Class.forName(driverName);
//获取数据库连接
conn = DriverManager.getConnection(url, username, password);
//创建PreparedStatement对象
String sql = "INSERT INTO students (id, name, age, gender) VALUES (?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
//读取Excel文件
File file = new File("students.xlsx");
FileInputStream fis = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
//遍历Excel表格
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case 0:
ps.setInt(1, (int) cell.getNumericCellValue());
break;
case 1:
ps.setString(2, cell.getStringCellValue());
break;
case 2:
ps.setInt(3, (int) cell.getNumericCellValue());
break;
case 3:
ps.setString(4, cell.getStringCellValue());
break;
default:
break;
}
}
//执行SQL语句
ps.executeUpdate();
}
//关闭PreparedStatement对象
ps.close();
//关闭数据库连接
conn.close();
//关闭Excel文件流
fis.close();
System.out.println("数据导入完成!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
代码中使用了Apache POI库来读取Excel文件,将读取到的数据插入到MySQL数据库中。你需要根据自己的实际情况修改代码中的数据库连接信息和SQL语句。
阅读全文