LoginSignup
14
13

More than 5 years have passed since last update.

libxlsxwriterを使って、C++でxlsxファイルを書き出す。

Last updated at Posted at 2016-03-28

Pythondで大量のデータをxlsxファイルに書き出すときに時間がかかるので、C++のライブラリを使ってみた。
使いどころとしては、大量のcsvやtsvデータをxlsxにExcelを使わずに書き出す場合。
速度比較を忘れたが、雲泥の差でC++が高速に書き出すことができた。
そのうち比較する。

xlsxファイルの場合1,048,576行、16384列まで対応してる。

libxlsxwriter

C用のシンプルなxlsx書き出しライブラリ。
Githubレポジトリで公開されている。

豊富な例が同梱されている。

インストール

インストール不要でも利用可能。
その場合はパスの指定が必用。

$ git clone https://github.com/jmcnamara/libxlsxwriter.git
$ cd libxlsxwriter
$ make
$ sudo make install

使い方

タブ区切りの標準入力をタブをセルの列区切りとし、引数で指定したファイルにxlsx形式で出力する。

サンプルコード

tsv2xlsx.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "xlsxwriter.h"

int main(int argc, char **argv) {
  // 引数チェック
  if (argc < 2){
    std::cerr << "Usage: " << argv[0] << " output_filename.xlsx" << std::endl;
  }

  // ExcelのWorkbookとWorksheetを作成
  lxw_workbook  *workbook  = workbook_new(argv[argc-1]); // argv[argc-1]はファイル名
  lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);

  std::vector<std::string> v_string;
  int row = 0;
  char input_text[51200]; // 標準入力のバッファー(string型で標準入力を受けるのがいいかも)
  while (std::cin.getline(input_text, sizeof(input_text))){
    row++;
    // 行数上限を超えないようにする。
    if(row == 1000000){
      break;
    }
    // 入力が空行の場合、書き込まない。
    if(!input_text[0]){
      continue;
    }
    // 入力をタブで区切る。
    boost::split(v_string, input_text, boost::is_any_of("\t"));

    // 1行出力
    for (int col = 0; col < v_string.size(); col++){
      worksheet_write_string(worksheet, row, col, v_string[col].c_str(), NULL);
    }
  }

  workbook_close(workbook);

  return 0;
}

コンパイルと実行

% g++ tsv2xlsx.cpp -o tsv2xlsx -lxlsxwriter
% cat test.tsv | ./tsv2xlsx test.xlsx
14
13
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
14
13