Delphi TQuery save to csv file

后端 未结 4 2178
太阳男子
太阳男子 2021-02-08 06:44

I want to export content of a TQuery to a CSV file without using a 3d part component(Delphi 7). From my knowledge this can not be accomplished with Delphi standard components.

4条回答
  •  星月不相逢
    2021-02-08 07:35

    The original question asked for a solution using a StringList. So it would be something more like this. It will work with any TDataSet, not just a TQuery.

    procedure WriteDataSetToCSV(DataSet: TDataSet, FileName: String);
    var
      List: TStringList;
      S: String;
      I: Integer;
    begin
      List := TStringList.Create;
      try
        DataSet.First;
        while not DataSet.Eof do
        begin
          S := '';
          for I := 0 to DataSet.FieldCount - 1 do
          begin
            if S > '' then
              S := S + ',';
            S := S + '"' + DataSet.Fields[I].AsString + '"';
          end;
          List.Add(S);
          DataSet.Next;
        end;
      finally
        List.SaveToFile(FileName);
        List.Free;
      end;
    end;
    

    You can add options to change the delimiter type or whatever.

提交回复
热议问题