Delphi从DataSet导出到Excel

来源:互联网 发布:acronis备份软件 编辑:程序博客网 时间:2024/04/30 07:32

 Delphi从DataSet导出到Excel

ExportDBGrid(toExcel:   Boolean);
      var  
          bm:   TBookmark;  
          col,   row:   Integer;  
          sline:   String;    
          mem:   TMemo;  
          ExcelApp:   Variant;    
      begin
          Screen.Cursor   :=   crHourglass;
          form1.DBGrid1.DataSource.DataSet.DisableControls;
          bm   :=   form1.DBGrid1.DataSource.DataSet.GetBookmark;
          form1.DBGrid1.DataSource.DataSet.First;
          //   create   the   Excel   object
          if   toExcel   then
          begin  
              ExcelApp   :=   CreateOleObject('Excel.Application');
              ExcelApp.WorkBooks.Add(xlWBatWorkSheet);  
              ExcelApp.WorkBooks[1].WorkSheets[1].Name   :=   'Grid   Data';  
          end;  
       
          //   First   we   send   the   data   to   a   memo  
          //   works   faster   than   doing   it   directly   to   Excel    
          mem   :=   TMemo.Create(nil);  
          mem.Visible   :=   false;    
          mem.Parent   :=   form1;  
          mem.Clear;    
          sline   :=   '';  
   
          //   add   the   info   for   the   column   names  
          for   col   :=   0   to   form1.DBGrid1.FieldCount-1   do  
              sline   :=   sline   +   form1.DBGrid1.Fields[col].DisplayLabel   +   #9;  
          mem.Lines.Add(sline);  
       
          //   get   the   data   into   the   memo  
          for   row   :=   0   to   form1.DBGrid1.DataSource.DataSet.RecordCount-1   do  
          begin  
              sline   :=   '';    
              for   col   :=   0   to   form1.DBGrid1.FieldCount-1   do  
                  sline   :=   sline   +   form1.DBGrid1.Fields[col].AsString   +   #9;  
              mem.Lines.Add(sline);
              form1.DBGrid1.DataSource.DataSet.Next;
          end;  
   
          //   we   copy   the   data   to   the   clipboard  
          mem.SelectAll;  
          mem.CopyToClipboard;  
   
          //   if   needed,   send   it   to   Excel  
          //   if   not,   we   already   have   it   in   the   clipboard  
          if   toExcel   then  
          begin  
              ExcelApp.Workbooks[1].WorkSheets['Grid   Data'].Paste;  
              ExcelApp.Visible   :=   true;  
          end;  
   
          FreeAndNil(mem);  
      //     FreeAndNil(ExcelApp);  
          form1.DBGrid1.DataSource.DataSet.GotoBookmark(bm);
          form1.DBGrid1.DataSource.DataSet.FreeBookmark(bm);
          form1.DBGrid1.DataSource.DataSet.EnableControls;  
          Screen.Cursor   :=   crDefault;  
      end;