C++を使用してExcelデータ検証をする

C++を使用してExcelデータ検証をする

はじめに

C++を使用してExcelデータを検証する方法を学びます。ExcelデータはCSVまたはXLSX形式で保存されており、それぞれの形式に応じた読み取り方法を紹介します。

CSVファイルの読み取り

CSVはテキスト形式のデータで、C++標準ライブラリのfstreamを使用して簡単に読み取ることができます。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

int main() {
    std::ifstream file("data.csv");
    std::string line;
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string cell;
        std::vector<std::string> row;
        while (std::getline(ss, cell, ',')) {
            row.push_back(cell);
        }
        // ここでデータを処理
    }
    return 0;
}

OpenXLSXを使用したExcelファイルの読み取り

OpenXLSXライブラリを使用してXLSXファイルを読み取る方法です。

#include "OpenXLSX.hpp"
#include <iostream>

int main() {
    OpenXLSX::XLDocument doc;
    doc.open("data.xlsx");
    auto sheet = doc.workbook().sheet(1);
    std::cout << sheet.cell("A1").value().get<std::string>() << std::endl;
    doc.close();
    return 0;
}

LibXLを使用したExcelファイルの読み取り

商用ライブラリであるLibXLを使用すると、より高度なExcel操作が可能です。

#include "libxl.h"
#include <iostream>

int main() {
    libxl::Book* book = xlCreateBook();
    if (book->load("data.xlsx")) {
        libxl::Sheet* sheet = book->getSheet(0);
        if (sheet) {
            std::cout << sheet->readStr(0, 0) << std::endl;
        }
    }
    book->release();
    return 0;
}

データ検証の方法

Excelデータの検証には以下のような方法があります。

  • 数値データの範囲チェック
  • 空白セルの検出
  • 重複データの検出
  • 日付フォーマットの確認

検証の具体例

例えば、CSVデータの各行の第2列が数値かどうかをチェックするコードは以下のようになります。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cctype>

bool isNumber(const std::string& str) {
    return !str.empty() && std::all_of(str.begin(), str.end(), ::isdigit);
}

int main() {
    std::ifstream file("data.csv");
    std::string line;
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string cell;
        std::vector<std::string> row;
        int colIndex = 0;
        while (std::getline(ss, cell, ',')) {
            if (colIndex == 1 && !isNumber(cell)) {
                std::cerr << "エラー: 数値であるべきデータが不正 (" << cell << ")" << std::endl;
            }
            colIndex++;
        }
    }
    return 0;
}

まとめ

C++を使用してExcelデータの検証を行う方法を紹介しました。簡単なCSVの読み取りから、OpenXLSXやLibXLを使ったXLSXファイルの操作まで、初心者でも理解しやすいように解説しました。用途に応じて適切なライブラリを選択し、データ検証に活用してください。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です