DBGridEh 倒出到 EXCEL

 

保存按钮click 如下:

 

procedure Tmainform.SaveToExcelClick(Sender: TObject);

  var ExpClass: TDBGridEhExportClass;
  Ext,GstrWorkDir,OutPath: string;
  SaveD: TSaveDialog;
begin
  if not DBGridEh1.DataSource.DataSet.Active then  abort;
  if DBGridEh1.DataSource.DataSet.RecordCount=0 then   abort;
  DBGridEh1.SetFocus;
  DBgrideh1.Selection.SelectAll;   //DBgridEh 全部内容输出

  if not DBGridEh1.datasource.dataset.Active then
  begin
    showmessage('无数据可输出,请先统计');
    abort;
  end;

  GstrWorkDir :='D:/';            //默认保存目录
  SaveD := TSaveDialog.Create(nil); // 新建 Savedialog对象
  SaveD.Options := [ofOverwritePrompt, ofHideReadOnly, ofEnableSizing];
  SaveD.Title := '另存为:';
  SaveD.InitialDir := GStrWorkdir;
  //saveD.DefaultExt :='XLS';
  SaveD.Filter := 'Text files (*.txt)|*.TXT|Comma separated values (*.csv)|*.CSV|HT' +
    'ML file (*.htm)|*.HTM|Rich Text Format (*.rtf)|*.RTF|Microsoft E' +
    'xcel Workbook (*.xls)|*.XLS';
  SaveD.FileName := 'Report'+FormatDateTime('yyyy-mm-dd',now);

  if (ActiveControl is TDBGridEh) then
    if SaveD.Execute then
    begin
      case SaveD.FilterIndex of
        1: begin ExpClass := TDBGridEhExportAsText; Ext := 'txt'; end;
        2: begin ExpClass := TDBGridEhExportAsCSV; Ext := 'csv'; end;
        3: begin ExpClass := TDBGridEhExportAsHTML; Ext := 'htm'; end;
        4: begin ExpClass := TDBGridEhExportAsRTF; Ext := 'rtf'; end;
        5: begin ExpClass := TDBGridEhExportAsXLS; Ext := 'xls'; end;
      else
        ExpClass := nil; Ext := '';
      end;
      if ExpClass <> nil then
      begin
        if UpperCase(Copy(SaveD.FileName, Length(SaveD.FileName) - 2, 3)) <>
          UpperCase(Ext) then
          SaveD.FileName := SaveD.FileName + '.' + Ext;
          OutPath:='Report'+FormatDateTime('yyyy-mm-dd',now) + '.' + Ext;
        //if  fileexists(SaveD.FileName) then
        // begin
        //  if application.MessageBox('文件已经存在,是否替换原有文件?','操作确认',MB_YESNO)=6 then
        //    SaveDBGridEhToExportFile(ExpClass, TDBGridEh(ActiveControl), SaveD.FileName, False);
        // end
        //else

            SaveDBGridEhToExportFile(ExpClass, TDBGridEh(ActiveControl), SaveD.FileName, False);
            Messagedlg(SaveD.FileName+'--- 文件保存成功!',mtConfirmation,[mbYES],0);
      end;
    end;
  TDBGridEh(ActiveControl).Selection.Clear;
end;

你可能感兴趣的:(ext,Microsoft,report,Excel,csv,rtf)