DbgridEh数据导出到Excel的方法(Delphi)

本文内容严重参考了网上其他牛人的代码,并做了一些修改,使得参数更加简单,结构更清晰,所以就厚着脸皮说是原创。

 

uses DBGridEhImpExp;

procedure TFrm_func.DbGridEhToExcel(ADgEh: TDBGridEh);
var
  ExpClass: TDBGridEhExportclass;
  Ext: string;
  FSaveDialog: TSaveDialog;
begin
  try
    if ADgEh.DataSource.DataSet.IsEmpty then
    begin
      Application.MessageBox(PChar(‘没有可导出的数据‘), PChar(‘提示‘), MB_OK +
        MB_ICONINFORMATION);
      exit;
    end;
    FSaveDialog := TSaveDialog.Create(Self);
    FSaveDialog.Filter :=
      ‘Excel 文档 (*.xls)|*.XLS|Text files (*.txt)|*.TXT|Comma separated values (*.csv)|*.CSV|HTML file (*.htm)|*.HTM|Word 文档 (*.rtf)|*.RTF‘;
    if FSaveDialog.Execute and (trim(FSaveDialog.FileName) <> ‘‘) then
    begin
      case FSaveDialog.FilterIndex of
        1:
          begin
            ExpClass := TDBGridEhExportAsXLS;
            Ext := ‘xls‘;
          end;
        2:
          begin
            ExpClass := TDBGridEhExportAsText;
            Ext := ‘txt‘;
          end;
        3:
          begin
            ExpClass := TDBGridEhExportAsCSV;
            Ext := ‘csv‘;
          end;
        4:
          begin
            ExpClass := TDBGridEhExportAsHTML;
            Ext := ‘htm‘;
          end;
        5:
          begin
            ExpClass := TDBGridEhExportAsRTF;
            Ext := ‘rtf‘;
          end;
      end;
      if ExpClass <> nil then
      begin
        if UpperCase(Copy(FSaveDialog.FileName, Length(FSaveDialog.FileName) -
          2, 3)) <> UpperCase(Ext) then
          FSaveDialog.FileName := FSaveDialog.FileName + ‘.‘ + Ext;
        if FileExists(FSaveDialog.FileName) then
        begin
          if application.MessageBox(‘文件名已存在,是否覆盖   ‘, ‘提示‘,
            MB_ICONASTERISK or MB_OKCANCEL) <> idok then
            exit;
        end;
        Screen.Cursor := crHourGlass;
        SaveDBGridEhToExportFile(ExpClass, ADgEh, FSaveDialog.FileName, true);
        Screen.Cursor := crDefault;
        MessageBox(Handle, ‘导出成功  ‘, ‘提示‘, MB_OK +
          MB_ICONINFORMATION);
      end;
    end;
    FSaveDialog.Destroy;
  except
    on e: exception do
    begin
      Application.MessageBox(PChar(e.message), ‘错误‘, MB_OK + MB_ICONSTOP);
    end;
  end;
end;

DbgridEh数据导出到Excel的方法(Delphi)

上一篇:使用Npgsql实现Linq To PostgreSQL


下一篇:C# Winform Excel的导出,根据excel模板导出数据