首页 运维百科文章正文

java excel导入数据库

运维百科 2025年11月19日 19:47 237 admin

Java实现Excel数据导入数据库的详细教程

在数据处理和分析领域,经常需要将Excel表格中的数据导入到数据库中进行存储和管理,使用Java编程语言,可以通过多种方式实现这一过程,本文将详细介绍如何使用Java读取Excel文件并将其数据导入到数据库中。

java excel导入数据库

我们需要准备一个包含数据的Excel文件,这里我们假设使用的是常见的.xlsx格式,我们将使用Apache POI库来处理Excel文件,因为它是一个功能强大且广泛使用的开源库,能够支持对Microsoft Office文档的读写操作。

添加依赖

在你的项目中加入Apache POI库的依赖,如果你使用的是Maven作为构建工具,可以在pom.xml文件中添加以下依赖:

<dependencies>
    <!-- Apache POI -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.2</version>
    </dependency>
    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
</dependencies>

读取Excel文件

使用Apache POI提供的API来读取Excel文件,下面是一个示例代码,演示如何打开一个Excel文件并遍历其中的所有工作表(Sheet)和行(Row):

java excel导入数据库

import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ExcelToDatabase {
    public static void main(String[] args) throws Exception {
        String filePath = "path/to/your/excel/file.xlsx";
        FileInputStream fis = new FileInputStream(new File(filePath));
        Workbook workbook = WorkbookFactory.create(fis);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            for (Row row : sheet) {
                // Assuming the first column is the id and the second column is the name
                Cell idCell = row.getCell(0);
                Cell nameCell = row.getCell(1);
                int id = (int) idCell.getNumericCellValue();
                String name = nameCell.getStringCellValue();
                // Insert data into database
                insertData(id, name);
            }
        }
        workbook.close();
        fis.close();
    }
    private static void insertData(int id, String name) throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password");
        String sql = "INSERT INTO table_name (id, name) VALUES (?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        statement.setString(2, name);
        statement.executeUpdate();
        statement.close();
        connection.close();
    }
}

注意事项

  • 确保你的数据库已经创建好,并且表中的列名与代码中的变量名相匹配。
  • 根据实际情况调整路径、用户名、密码等参数。
  • 上述代码仅作为示例,实际应用时可能需要根据具体需求进行修改和完善。

通过上述步骤,你就可以成功地将Excel文件中的数据导入到数据库中了,希望这篇教程对你有所帮助!

标签: Java

发表评论

丫丫技术百科 备案号:新ICP备2024010732号-62