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?

More than 5 years have passed since last update.

C++builderでTStringGridからCSVを書き出す

Last updated at Posted at 2015-04-22

セル内にカンマが有る場合の処理のため、ダブルクォーテーションで全体を囲むか、カンマを「\,」に変換しておく。
行数によってはメモリ不足に注意。

FireMonkey.h
///std::unique_ptr用(C++11対応の環境用)
# include <memory>
///引数double_quotationの初期値をfalseにしておくと、デフォルトでは¥,になる。
void __fastcall FunctionSaveCSV(const UnicodeString &var_filepath,TStringGrid *var_string_grid, const bool &double_quotation = false) ;
FireMonkey.cpp
void __fastcall TForm1::FunctionSaveCSV(const UnicodeString &var_filepath,TStringGrid *var_string_grid, const bool &double_quotation) {
	std::unique_ptr<TStringList>var_list(new TStringList); // csv書き出し用
	for (int i = 0; i < var_string_grid->RowCount; i++) {
		UnicodeString var; // 1行にまとめるときに使う。
		for (int i2 = 0; i2 < var_string_grid->ColumnCount; i2++) {
			UnicodeString tmp_c; // 1セルの一時保存
			tmp_c = var_string_grid->Cells[i2][i];
			if (double_quotation == true) {
				// セルをダブルクォーテーションで囲む
				tmp_c = L"\"" + tmp_c + L"\"";
			}
			else {
				// セルをダブルクォーテーションで囲わない場合、文字列中のカンマは全て\,に変換する
				tmp_c = StringReplace(tmp_c, L"\\,", L",",
					TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
				tmp_c = StringReplace(tmp_c, L",", L"\\,",
					TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
			}
			// 改行は別の文字に変換するか、削除する。
			tmp_c = StringReplace(tmp_c, L"\n", L"",
				TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
			if (i2 < var_string_grid->ColumnCount) {
				tmp_c += L",";
			}
			else {
				tmp_c += L"\n";
			}
			var += tmp_c;
		}
		var_list->Add(var);
	}
	var_list->SaveToFile(var_filepath);
}

読み込みはこちら
C++builderでCSVを読み込んでTStringGridに表示

0
0
3

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?