0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaでExcelデータをSQLiteデータベースにインポートする方法

Posted at

業務でよく使われるExcelファイルから、データベースへの自動インポートは非常に便利です。手動でデータを移す作業は時間がかかり、ミスも発生しやすいため、Javaを使った自動化によって効率と信頼性が大幅に向上します。

この記事では、Javaを使ってExcelファイルからデータを読み取り、SQLiteデータベースに挿入する方法を紹介します。

使用する技術

  • Free Spire.XLS for Java:Excelファイルの読み取りに使用
  • SQLite:軽量で組み込み型のデータベース
  • JDBC:Javaでデータベースに接続するためのAPI

実装の流れ

  1. Excelファイルを読み込み、行ごとにセルの内容を取得
  2. 最初の行を列名として使用し、SQLiteテーブルを生成
  3. JDBCを使って行ごとのデータをデータベースに挿入

Javaコード例:Excel → SQLite

import com.spire.xls.*;
import java.sql.*;
import java.util.*;

public class ExcelToSQLite {
    public static void main(String[] args) {
        String excelPath = "example.xlsx"; // Excelファイルのパス
        String dbPath = "jdbc:sqlite:excel_data.db"; // SQLiteデータベースのパス

        // Excelファイルを読み込む
        Workbook workbook = new Workbook();
        workbook.loadFromFile(excelPath);

        try (Connection conn = DriverManager.getConnection(dbPath)) {
            System.out.println("SQLiteデータベースに接続しました。");

            for (Worksheet sheet : workbook.getWorksheets()) {
                // ワークシート名をテーブル名として使用(記号を除去)
                String tableName = sheet.getName().replaceAll("[^a-zA-Z0-9_]", "_");

                CellRange range = sheet.getAllocatedRange();
                int rowCount = range.getRowCount();     // 行数
                int colCount = range.getColumnCount();  // 列数

                // 1行目を列名として取得
                List<String> columns = new ArrayList<>();
                for (int col = 1; col <= colCount; col++) {
                    String colName = sheet.getCellRange(1, col).getText().trim();
                    if (colName.isEmpty()) {
                        colName = "Column" + col;
                    }
                    columns.add(colName.replaceAll("[^a-zA-Z0-9_]", "_"));
                }

                // テーブル作成SQLを構築
                StringBuilder createSQL = new StringBuilder("CREATE TABLE IF NOT EXISTS `" + tableName + "` (");
                for (String col : columns) {
                    createSQL.append("`").append(col).append("` TEXT,");
                }
                createSQL.setLength(createSQL.length() - 1); // 最後のカンマを削除
                createSQL.append(");");

                try (Statement stmt = conn.createStatement()) {
                    stmt.execute(createSQL.toString()); // テーブル作成実行
                }

                // データ挿入用のSQL(プレースホルダー付き)
                String placeholders = String.join(",", Collections.nCopies(columns.size(), "?"));
                String insertSQL = "INSERT INTO `" + tableName + "` (" + String.join(",", columns) + ") VALUES (" + placeholders + ")";

                try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
                    for (int row = 2; row <= rowCount; row++) {
                        for (int col = 1; col <= colCount; col++) {
                            String value = sheet.getCellRange(row, col).getText();
                            pstmt.setString(col, value); // パラメータを設定
                        }
                        pstmt.executeUpdate(); // 行を挿入
                    }
                }

                System.out.println("ワークシート「" + tableName + "」のデータをインポートしました。");
            }

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

まとめ

Spire.XLSとJDBCを組み合わせることで、Excelファイルのデータを簡単にSQLiteへ取り込むことが可能です。初期データの登録や、ユーザーから提供されたファイルの一括登録などに活用できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?