共计 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 网 – 提供最优质的资源集合!