Exporting data from a DBGrid to Excel

前端 未结 2 2047
陌清茗
陌清茗 2020-12-10 08:32

I wanted to know if anyone ones a way that I can export data from a DBGrid to Excel ? I am using Delphi 7 , Excel 2007 and ADO .
Any help will be appreciated.

2条回答
  •  暖寄归人
    2020-12-10 08:52

    It is working by using Tfilestream component

    procedure TForm2.ExportdatatoexcelClick(Sender: TObject);
     var
      Stream: TFileStream;
      i: Integer;
      OutLine,f: string;
      sTemp,s: string;
    begin
      Stream := TFileStream.Create('D:\Yogesh Delphi\employee1.csv', fmCreate);
      try
           s := string(adotable1.Fields[0].FieldName);
    
          for I := 1 to adotable1.FieldCount - 1 do
           begin
            s:= s+ ',' + string(adotable1.Fields[I].FieldName);
           end;
             s:= s+ #13#10;
            stream.Write(s[1], Length(s) * SizeOf(Char));
           {S := '';
          for I := 0 to adotable1.FieldCount - 1 do
            begin
             S := (adotable1.Fields[I].FieldName);
            outline := OutLine+S + ' ,';
            end; }
    
        while not adotable1.Eof do
        begin
          // You'll need to add your special handling here where OutLine is built
           s:='';
          OutLine := '';
          for i := 0 to adotable1.FieldCount - 1 do
          begin
            sTemp := adotable1.Fields[i].AsString;
            // Special handling to sTemp here
            OutLine := OutLine + sTemp +',';
          end;
          // Remove final unnecessary ','
          SetLength(OutLine, Length(OutLine) - 1);
          // Write line to file
          Stream.Write(OutLine[1], Length(OutLine) * SizeOf(Char));
          // Write line ending
          Stream.Write(sLineBreak, Length(sLineBreak));
          adotable1.Next;
        end;
    
      finally
        Stream.Free;  // Saves the file
      end;
        showmessage('Records Successfully Exported.') ;
    end;
        {Yog}
    

提交回复
热议问题