Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
Delphiデータベース

WinSoft CSVライブラリで、超高速CSVファイル処理

CSV(Comma Separated Value)形式は、さまざまなスプレッドシートプログラム間でのデータ交換/変換に永く利用されてきました。CSVは、新旧いずれのアプリケーションでもデータのインポート/エクスポート機能として使用でき、実質、コンピューティング環境におけるすべてのアーキテクチャ間でのデータ交換のデファクトスタンダードであると言えます。

DelphiにおけるCSVファイルの作成や操作は、WinSoftが提供する強力なCSVライブラリを使用することで非常に簡単になります。

インストール

image-10-2655868
メニューから[ツール|オプション|言語|Delphi|ライブラリ]を選択

https://winsoft.sk/csv.htm から最新バージョンをダウンロードし、ダウンロードファイルをデフォルトのコンポーネントフォルダーに解凍します。

このライブラリは、非ビジュアルライブラリですので、IDE上でインストール操作を行う必要はありません。

使用しているDelphiのバージョンとプラットフォームに応じて、[ツール|オプション|言語|Delphi|ライブラリ]と選択し、「ライブラリパス」にフォルダを追加します。

サンプル

以下は、コンタクト先管理用の単純なアプリケーションに、汎用的なインポート/エクスポート機能を実装する例です。

データセットから新しいCSVファイルを作成(エクスポート機能)

procedure ExportToFile(ADataset : TDataset; AFileName : string)
var
   CSV : TCSVWriter; i : integer;
   value : string;
begin  
  
  CSV:=TCsvWriter.Create(AFileName)
  
  ADataset.First;
  
  // first we need to create header for fieldnames
  for i := 0 to ADAtaSet.FieldList.Count - 1 do begin
    CSV.Write(ADataset.Fields[i].fieldName);    
  end;
 
  // now we will looping over Dataset to set record values
  try 
    while not ADataset.eof do begin
      // Append a new line
      CSV.NextLine;
      for i := 0 to ADataSet.FieldList.Count - 1 do begin
        // special case for date and datetime fields to avoid conflicts with date separators
        case ADataset.Fields[i].FieldType of
          ftDate : Value:=FormatDateTime('yyyymmdd', ADataset.Fields[i].AsDatetime);
          ftDateTime : Value:=FormatDateTime('yyyymmddhhnnsszzz', ADataset.Fields[i].AsDatetime);                    
          ftTime : Value:=FormatDateTime('hhnnsszzz', ADataset.Fields[i].AsDatetime);                              
        else
          Value:=ADataset.Fields[i].AsDatetime;
        end; 
      end;
      ADataset.Next;
    end;
  finally
    CSV.Free;    
  end;
end;

データセットへ既存のCSVファイルを読み込み(インポート機能)

procedure ImportFromFile(ADataset : TDataset; AFilenanme ; string);
var  
  CSV : TCSV;
  i,j : integer;
  Value, FieldName : string;
  slFields : TStringList;
  fs: TFormatSettings;  
begin
  if not FileExists(AFileName) then 
    Exception.Create('File '+AFileName +' does not exists');
  
  CSV := TCSV.Create;
  
  slFields:=TStringList.Create;
  
  fs := TFormatSettings.Create;
  fs.DateSeparator := '';
  fs.ShortDateFormat := 'yyyymmdd';
  fs.TimeSeparator := '';
  fs.ShortTimeFormat := 'hhmmss';
  fs.LongTimeFormat := 'hhmmss'; 
 
  try  
    CSV.LoadUtf8File(AFileName);
 
    // mapping for proper fields names info on first line of file
    for i := CSV.FieldsCount[0] do begin
      slFields.Add(CSV.Fields[0, i])
    end;
 
    for i:= 1 to CSV.LineCount - 1 do begin
      ADataset.Append;
      for j := 0 to CSV.FieldCount[i] do begin
        // get field value of current record
        Value:=CSV.Fields[i, j];
        FieldName:=slFiels.Strings[j];
 
        case ADataset.FieldByName(FieldName).FieldType of
          ftDate , ftDateTime, ftTime: 
            Value:= StrToDateTime(Value);
        end; 
 
        ADataset.FieldByName(FieldName).Value:=Value;
      end;
      ADataSet.Post;
    end;
  finally
    CSV.Free;    
    slField.Free;
    fs.Free;
  end;
end;

DelphiとC++Builderで利用できるWINSOFT CSVの全体像について、こちらのページでその詳細をご確認ください。

CSVライブラリは、WinSoft社の製品です。この記事に記載された機能を利用するには、WinSoft社のサイトからCSVライブラリを購入する必要があります。CSVライブラリに関するサポートは、WinSoft社によって提供されます。

RAD Studio 13.1 Florence Now Available See What's New in RAD Studio 13.1 Delphi is 31 - Webinar Replay

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.

Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES