这样的文张很多,到网上查一下就知道了

解决方案 »

  1.   

    procedure Tbrowse.ExportToExcel(defaultName: string;
      Grid: TDBGridEh);
    var
        ls_FileName:string;
        I,K,M,N:integer;
          y       :integer;
        tsList  :TStringList;
        s       :string;
        aSheet:Variant;
    begin
      if not Grid.DataSource.DataSet.Active then // if 5
      begin
        Application.Messagebox('未与数据库连接!','消息',mb_OK+mb_IconStop);
        Exit;
      end; //end if 5
      Grid.DataSource.DataSet.DisableControls;
      //如果未装Excel,则退出。
      try   //try 30
        Excel.Connect;                  // 打开Excel
        Excel.Visible[0]:=false;         // 显示Excel
        Excel.Workbooks.Add(xlWBATWorksheet,0);
        aSheet:=excel.Worksheets.Item[1];
      except
        Application.MessageBox('无法打开Xls文件,请确认已经安装EXCEL.','警告',mb_OK+mb_IconStop);
        Exit;
      end;   //end try 30
      Dlg_SaveToFile.FileName:=defaultName;
      if not Dlg_SaveToFile.Execute Then Exit;
      ls_FileName:=Dlg_SaveToFile.FileName;  try  //try 15
        K:=1;
        N:=Grid.Columns.count;
        I:=Grid.DataSource.DataSet.RecordCount;
        tsList:=TStringList.Create;
        FormProgress:=TFormProgress.Create (self);
        FormProgress.Show;
            try
                Grid.DataSource.DataSet.first;
                while not Grid.DataSource.DataSet.Eof do
                    begin
                        s:='';
                        for y:=0 to n-1 do
                        begin
                            s:=s+Grid.DataSource.DataSet.Fields[y].AsString+#9;
                            Application.ProcessMessages;
                        end;
                        tsList.Add(s);
                        FormProgress.ProgressBar1.Position:=Trunc((K*100)/I);
                        FormProgress.Refresh;
                        INC(K);
                        Grid.DataSource.DataSet.next;
                    end;
                Clipboard.AsText:=tsList.Text;
        finally
            tsList.Free;
        end;
        Excel.Disconnect;
        aSheet.Paste;
        aSheet.Saveas(ls_FileName);
        MessageBox(Application.Handle,'数据导出完毕!','系统提示',MB_ICONINFORMATION or MB_OK);
        Excel.Quit;
        aSheet:=Unassigned; //释放VARIANT变量    except
          Application.Messagebox('数据导出错误!','消息',mb_OK+MB_ICONINFORMATION);
          Exit;
        end;   //end try 80
    Excel是其中的一个实例!