要将Excel导入数据库,可以使用Java中的Apache POI库来读取Excel文件,然后使用JDBC连接到数据库并将数据插入到数据库中。
以下是一个简单的示例代码:
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.xssf.usermodel.XSSFWorkbook; public class ExcelToDatabase {public static void main(String[] args) {
String excelFilePath = “path/to/excel/file.xlsx”;
String url = “jdbc:mysql://localhost:3306/database_name”;
String username = “username”;
String password = “password”;
try (Connection connection = DriverManager.getConnection(url, username, password)) {
FileInputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
String insertQuery = "INSERT INTO table_name (column1, column2, column3) VALUES
(?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(insertQuery);
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cell1 = row.getCell(0);
Cell cell2 = row.getCell(1);
Cell cell3 = row.getCell(2);
String value1 = cell1.getStringCellValue();
String value2 = cell2.getStringCellValue();
String value3 = cell3.getStringCellValue();
statement.setString(1, value1);
statement.setString(2, value2);
statement.setString(3, value3);
statement.executeUpdate();
}
workbook.close();
System.out.println(“Excel imported to database successfully!”);
} catch (Exception e) {
e.printStackTrace();
}
} }
请确保已添加Apache POI和MySQL JDBC驱动的依赖项。在代码中,需要将path/to/excel/file.xlsx
替换为实际的Excel文件路径,jdbc:mysql://localhost:3306/database_name
替换为实际的数据库连接URL,username
和password
替换为实际的数据库用户名和密码,table_name
替换为实际的数据库表名,column1
、column2
和column3
替换为实际的数据库表列名。