java excel导入 数据库 代码
时间: 2023-10-13 14:04:55 浏览: 87
java excel导入数据库
可以使用 Apache POI 库来读取 Excel 文件,然后使用 JDBC 连接数据库,将数据写入数据库中。以下是一个简单的示例:
```
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) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
String excelFile = "data.xlsx";
String tableName = "mytable";
try {
// Load Excel file
FileInputStream file = new FileInputStream(excelFile);
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
// Connect to database
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
// Prepare SQL statement
String sql = "INSERT INTO " + tableName + " VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
// Iterate over rows and cells
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.setDouble(2, cell2.getNumericCellValue());
statement.setBoolean(3, cell3.getBooleanCellValue());
statement.executeUpdate();
}
// Close resources
statement.close();
connection.close();
file.close();
System.out.println("Data imported successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请记得替换相应的数据库信息、Excel 文件名和表名。
阅读全文