共計 2230 個字符,預計需要花費 6 分鐘才能閱讀完成。
要將 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 替換為實際的數據庫表列名。
丸趣 TV 網 – 提供最優質的資源集合!