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?

エクセルファイルに記載されているSQLのステップ数をカウントするjavaプログラムを作ってみよう(動作確認中)

Last updated at Posted at 2024-09-18

この要件に沿ったJavaプログラムを作成するためには、以下の主要なライブラリを使用することが必要です。

Apache POI: Excelファイルの読み取りに使用します。
OpenCSV: CSVファイルの書き込みに使用します。
java.util.Properties: プロパティファイルの読み込みに使用します。
これらのライブラリを含めたJavaプログラムのサンプルコードを以下に示します。

必要なライブラリ
以下のMaven依存関係をプロジェクトに追加してください。

xml
<dependencies>
    <!-- Apache POI for reading Excel files -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.2</version>
    </dependency>

    <!-- OpenCSV for writing CSV files -->
    <dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>5.5.2</version>
    </dependency>
</dependencies>

ディレクトリ構造とプロパティファイル
ディレクトリ構造は次のようにします。

bash
/project-root
    /src
        /main
            /java
                - Main.java
            /resources
                - config.properties

config.properties ファイル内容(src/main/resources/config.properties):

properties
excel.folder.path=path/to/excel/files
output.csv.path=path/to/output/result.csv

path/to/excel/filesとpath/to/output/result.csvを実際のパスに置き換えてください。

Javaプログラムコード
以下がJavaプログラムの全コードです。

java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.opencsv.CSVWriter;

import java.io.*;
import java.nio.file.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            // プロパティファイルの読み込み
            System.out.println("プロパティファイルを読み込み中...");
            InputStream input = Main.class.getClassLoader().getResourceAsStream("config.properties");
            if (input == null) {
                System.out.println("config.properties ファイルが見つかりません。");
                return;
            }
            properties.load(input);

            String excelFolderPath = properties.getProperty("excel.folder.path");
            String outputCsvPath = properties.getProperty("output.csv.path");

            System.out.println("Excelフォルダパス: " + excelFolderPath);
            System.out.println("出力CSVパス: " + outputCsvPath);

            // フォルダパスの存在をチェック
            Path excelFolder = Paths.get(excelFolderPath);
            if (!Files.exists(excelFolder)) {
                System.out.println("指定されたフォルダが存在しません: " + excelFolderPath);
                return;
            }

            // 出力用のCSVファイルを作成
            try (CSVWriter writer = new CSVWriter(new FileWriter(outputCsvPath))) {
                // ヘッダを書き込む(Excelファイル名、シート名、ステップ数のみ)
                writer.writeNext(new String[]{"File Name", "Sheet Name", "SQL Step Count"});
                System.out.println("フォルダ内のExcelファイルを処理中...");

                // 指定フォルダ内のすべてのExcelファイルを処理
                Files.walk(excelFolder)
                        .filter(Files::isRegularFile)
                        .filter(path -> path.toString().endsWith(".xlsx"))
                        .forEach(path -> {
                            String fileName = path.getFileName().toString(); // パスからファイル名だけを取得
                            System.out.println("ファイルを処理中: " + fileName);
                            processExcelFile(fileName, path.toString(), writer);
                        });
            }

            System.out.println("CSVファイルが出力されました: " + outputCsvPath);
        } catch (IOException e) {
            System.out.println("ファイル処理中にエラーが発生しました: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // Excelファイルを処理してSQLステップ数を取得し、ファイル名、シート名、ステップ数をCSVに記載
    private static void processExcelFile(String fileName, String filePath, CSVWriter writer) {
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            // 各シートを順に処理
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                System.out.println("シートを処理中: " + sheet.getSheetName());

                int totalStepCount = 0;
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        if (cell.getCellType() == CellType.STRING) {
                            String cellValue = cell.getStringCellValue();
                            if (isSQL(cellValue)) {
                                totalStepCount += countSteps(cellValue); // 各SQLのステップ数を合計
                            }
                        }
                    }
                }

                // SQLが含まれている場合のみCSVに書き込む
                if (totalStepCount > 0) {
                    writer.writeNext(new String[]{fileName, sheet.getSheetName(), String.valueOf(totalStepCount)});
                    System.out.println("ファイル: " + fileName + ", シート: " + sheet.getSheetName() + ", ステップ数: " + totalStepCount);
                }
            }
        } catch (IOException e) {
            System.out.println("Excelファイルの処理中にエラーが発生しました: " + filePath + " エラーメッセージ: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // セルの内容がSQL文かどうかを判定
    private static boolean isSQL(String text) {
        // SQL文とみなすための簡単なチェック (SELECT, INSERT, UPDATE, DELETEのいずれかが含まれるか)
        String trimmedText = text.trim().toUpperCase();
        return trimmedText.startsWith("SELECT") || trimmedText.startsWith("INSERT") ||
               trimmedText.startsWith("UPDATE") || trimmedText.startsWith("DELETE");
    }

    // ステップ数(行数)をカウント
    private static int countSteps(String sqlText) {
        // SQL文の行数をカウント
        return (int) Arrays.stream(sqlText.split("\n")).count();
    }
}

xml
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.2</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

プログラムの動作について
プロパティファイルの読み込み: config.properties からExcelファイルのあるフォルダパスと、出力するCSVファイルのパスを取得します。
Excelファイルの読み取り: 指定フォルダ内の全てのExcelファイル(.xlsx)を処理します。
SQL文の抽出: Excelファイル内の各セルの内容がSQL文であるかどうかを簡単な判定でチェックします(この例ではSQL文の先頭がSELECT、INSERT、UPDATE、DELETEである場合をSQL文とみなしています)。
ステップ数のカウント: SQL文の行数をカウントします。
CSVファイルへの出力: ファイル名、SQL文、ステップ数をCSVファイルに書き出します。
注意点
isSQL メソッドのSQL文判定は簡略化されています。実際の要件に応じてSQL判定ロジックを調整してください。
Excelファイルのフォーマットやセルの内容によってはエラーが発生する可能性があるので、必要に応じて例外処理を追加してください。

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?