Exporting data from a DBGrid to Excel

前端 未结 2 2050
陌清茗
陌清茗 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:59

    If you want a fast export of raw data, just export your recordset (ADODataset.recordset) with something like that:

    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;
    

提交回复
热议问题