0
点赞
收藏
分享

微信扫一扫

Javaexcel文件读取,插入到数据库中

你可以使用Java的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.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelToDatabase {
    public static void main(String[] args) {
        String excelFilePath = "path/to/your/excel/file.xlsx";
        String dbUrl = "jdbc:mysql://localhost:3306/your_database";
        String username = "your_username";
        String password = "your_password";

        try (Connection conn = DriverManager.getConnection(dbUrl, username, password)) {
            FileInputStream fileInputStream = new FileInputStream(excelFilePath);
            Workbook workbook = new XSSFWorkbook(fileInputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                // Assuming the data starts from the second row, change as per your requirement
                if (row.getRowNum() == 0) continue;

                String column1Value = row.getCell(0).getStringCellValue();
                int column2Value = (int) row.getCell(1).getNumericCellValue();

                // Insert the data into the database
                String sql = "INSERT INTO your_table_name (column1, column2) VALUES (?, ?)";
                PreparedStatement statement = conn.prepareStatement(sql);
                statement.setString(1, column1Value);
                statement.setInt(2, column2Value);
                statement.executeUpdate();
            }

            System.out.println("Data inserted successfully!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,你需要将以下部分替换为你自己的信息:

  • excelFilePath:Excel文件的路径。
  • dbUrl:数据库的URL。
  • usernamepassword:数据库的用户名和密码。
  • your_table_name:要插入数据的表名。

请注意,你需要将正确的数据库驱动程序添加到你的项目依赖中。这个示例假设你正在使用MySQL数据库,如有需要,请根据使用的数据库更改代码中的相关部分。

另外,请确保在使用JDBC连接时使用安全的方式,如使用加密连接、参数化查询等,以避免潜在的安全问题。

举报

相关推荐

0 条评论