Delphi TQuery save to csv file

后端 未结 4 2175
太阳男子
太阳男子 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:47

    This is like the Rob McDonell solution but with some enhancements: header, escape chars, enclosure only when required, and ";" separator. You can easily disable this enhancements if not required.

    procedure SaveToCSV(DataSet: TDataSet; FileName: String);
    const
      Delimiter: Char = ';'; // In order to be automatically recognized in Microsoft Excel use ";", not ","
      Enclosure: Char = '"';
    var
      List: TStringList;
      S: String;
      I: Integer;
      function EscapeString(s: string): string;
      var
        i: Integer;
      begin
        Result := StringReplace(s,Enclosure,Enclosure+Enclosure,[rfReplaceAll]);
        if (Pos(Delimiter,s) > 0) OR (Pos(Enclosure,s) > 0) then  // Comment this line for enclosure in every fields
            Result := Enclosure+Result+Enclosure;
      end;
      procedure AddHeader;
      var
        I: Integer;
      begin
        S := '';
        for I := 0 to DataSet.FieldCount - 1 do begin
          if S > '' then
            S := S + Delimiter;
          S := S + EscapeString(DataSet.Fields[I].FieldName);
        end;
        List.Add(S);
      end;
      procedure AddRecord;
      var
        I: Integer;
      begin
        S := '';
        for I := 0 to DataSet.FieldCount - 1 do begin
          if S > '' then
            S := S + Delimiter;
          S := S + EscapeString(DataSet.Fields[I].AsString);
        end;
        List.Add(S);
      end;
    begin
      List := TStringList.Create;
      try
        DataSet.DisableControls;
        DataSet.First;
        AddHeader;  // Comment if header not required
        while not DataSet.Eof do begin
          AddRecord;
          DataSet.Next;
        end;
      finally
        List.SaveToFile(FileName);
        DataSet.First;
        DataSet.EnableControls;
        List.Free;
      end;
    end;
    

提交回复
热议问题