java读取excel文件并导入数据库的代码
时间: 2023-09-27 12:06:04 浏览: 107
好的,下面是一个简单的 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 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 ExcelToDatabase {
public static void main(String[] args) {
String fileName = "path/to/excel/file.xlsx";
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String dbUser = "root";
String dbPassword = "password";
try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword)) {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheetAt(0);
String sql = "INSERT INTO mytable (col1, col2, col3) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
int rowNumber = 0;
for (Row row : sheet) {
if (rowNumber == 0) { // Skip header row
rowNumber++;
continue;
}
Cell cell1 = row.getCell(0);
Cell cell2 = row.getCell(1);
Cell cell3 = row.getCell(2);
pstmt.setString(1, cell1.getStringCellValue());
pstmt.setString(2, cell2.getStringCellValue());
pstmt.setString(3, cell3.getStringCellValue());
pstmt.executeUpdate();
rowNumber++;
}
pstmt.close();
fis.close();
workbook.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,此示例代码需要导入 Apache POI 和 MySQL JDBC 驱动程序。
阅读全文