java导入excel表到数据库多张表中
时间: 2024-02-19 16:55:53 浏览: 162
以下是Java导入Excel表到数据库多张表中的示例代码:
```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 ExcelImporter {
public static void main(String[] args) {
String excelFilePath = "path/to/excel/file.xlsx";
try {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Iterator<Sheet> sheetIterator = workbook.iterator();
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
String tableName = sheet.getSheetName();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
// 获取数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password");
// 构建插入语句
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO ").append(tableName).append(" VALUES (");
for (int i = 0; i < row.getLastCellNum(); i++) {
sql.append("?,");
}
sql.deleteCharAt(sql.length() - 1);
sql.append(")");
// 创建预编译语句
PreparedStatement statement = connection.prepareStatement(sql.toString());
int cellIndex = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
statement.setString(cellIndex + 1, cell.getStringCellValue());
cellIndex++;
}
// 执行插入语句
statement.executeUpdate();
// 关闭连接和语句
statement.close();
connection.close();
}
}
workbook.close();
inputStream.close();
System.out.println("Excel导入到数据库成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,上述代码中的数据库连接信息需要根据实际情况进行修改。此外,还需要添加Apache POI和MySQL驱动的依赖。
阅读全文