java 识别excel文件数据 批量导入
时间: 2024-05-07 09:19:43 浏览: 12
可以使用 Apache POI 库来读取 Excel 文件并将数据导入到数据库中。
下面是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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 ExcelImporter {
public static void main(String[] args) throws Exception {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
// Excel 文件路径
String excelFilePath = "/path/to/excel/file.xlsx";
// 打开 Excel 文件
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
// 读取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
// 遍历每一行并将数据插入到数据库中
String sql = "INSERT INTO my_table (col1, col2, col3) VALUES (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
for (Row row : sheet) {
Cell cell1 = row.getCell(0);
Cell cell2 = row.getCell(1);
Cell cell3 = row.getCell(2);
statement.setString(1, cell1.getStringCellValue());
statement.setInt(2, (int) cell2.getNumericCellValue());
statement.setBoolean(3, cell3.getBooleanCellValue());
statement.executeUpdate();
}
// 关闭资源
statement.close();
conn.close();
inputStream.close();
workbook.close();
}
}
```
在实际使用中,需要根据实际情况修改代码中的数据库连接信息、Excel 文件路径、插入语句以及列的顺序和数据类型等。