将数据从DBGrid导出到Excel

时间:2013-06-12 05:57:37

标签: excel delphi delphi-7 ado

我想知道是否有人可以将数据从DBGrid导出到Excel?我正在使用Delphi 7,Excel 2007和ADO 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:13)

如果您想快速导出原始数据,只需将您的记录集(ADODataset.recordset)导出为:

procedure ExportRecordsetToMSExcel(DestName: string; Data: _Recordset);
var
  ovExcelApp: OleVariant;
  ovExcelWorkbook: OleVariant;
  ovWS: OleVariant;
  ovRange: OleVariant;
begin
  ovExcelApp := CreateOleObject('Excel.Application'); //If Excel isnt installed will raise an exception
  try
    ovExcelWorkbook   := ovExcelApp.WorkBooks.Add;
    ovWS := ovExcelWorkbook.Worksheets.Item[1]; // go to first worksheet
    ovWS.Activate;
    ovWS.Select;
    ovRange := ovWS.Range['A1', 'A1']; //go to first cell
    ovRange.Resize[Data.RecordCount, Data.Fields.Count];
    ovRange.CopyFromRecordset(Data, Data.RecordCount, Data.Fields.Count); //this copy the entire recordset to the selected range in excel
    ovWS.SaveAs(DestName, 1, '', '', False, False);
  finally
    ovExcelWorkbook.Close(SaveChanges := False);
    ovWS := Unassigned;
    ovExcelWorkbook := Unassigned;
    ovExcelApp := Unassigned;
  end;
end;

答案 1 :(得分:0)

它正在使用Tfilestream组件

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}