java导入excel到数据库
时间: 2023-09-13 20:07:56 浏览: 88
java实现excel导入数据库
可以使用Apache POI和JDBC来实现Java导入Excel到数据库的功能。
下面是一个简单的示例代码:
1. 导入POI和JDBC的库:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
```
2. 实现导入Excel到数据库的方法:
```java
public static void importExcelToDatabase(String filePath, String tableName) throws Exception {
FileInputStream file = new FileInputStream(new File(filePath));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
PreparedStatement pstmt = null;
String sql = "INSERT INTO " + tableName + " (column1, column2, column3, column4) VALUES (?, ?, ?, ?)";
pstmt = con.prepareStatement(sql);
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
if (row.getRowNum() == 0) {
continue;
}
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
pstmt.setString(cell.getColumnIndex() + 1, cell.getStringCellValue());
break;
case NUMERIC:
pstmt.setDouble(cell.getColumnIndex() + 1, cell.getNumericCellValue());
break;
case BOOLEAN:
pstmt.setBoolean(cell.getColumnIndex() + 1, cell.getBooleanCellValue());
break;
default:
pstmt.setString(cell.getColumnIndex() + 1, "");
break;
}
}
pstmt.executeUpdate();
}
con.close();
file.close();
}
```
3. 调用方法:
```java
importExcelToDatabase("path/to/file.xlsx", "mytable");
```
其中,第一个参数是Excel文件的路径,第二个参数是要插入数据的表名。
注意:该示例只适用于Excel文件中只有一张表格的情况,如果Excel文件中有多张表格,需要根据需要进行修改。
阅读全文