要將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
替換為實際的數據庫表列名。