delphi从dbgrid导出数据保存成excel文件


本文整理自网络,侵删。

 

uses ComObj;

 

function TForm1.ExportDBGrid(DBGrid: TDBGrid; SheetName: string): boolean;//直接保存,不显示EXCEL

var
c, r, i, j: integer;
app: Olevariant;
TempFileName, ResultFileName: string;
begin
try
    result := True;
      app := CreateOLEObject('Excel.application');
    // app.WorkBooks.Add(xlWBatWorkSheet);   
    except
      Application.MessageBox('Excel没有正确安装!','警告',MB_OK);
      result := False;
      exit;
    end;
    SaveDialog1.DefaultExt := 'xls';
    SaveDialog1.FileName := SheetName;
    if SaveDialog1.Execute then
      TempFileName := SaveDialog1.FileName
    else
      Exit;
    app.Workbooks.add;
    app.Visible := false;
    Screen.Cursor := crHourGlass;
    DBGrid.DataSource.DataSet.First;
    c := DBGrid.DataSource.DataSet.FieldCount;
    r := DBGrid.DataSource.DataSet.RecordCount;
    Application.ProcessMessages;
    for i := 0 to c - 1 do
      app.cells(1, 1 + i) := DBGrid.DataSource.DataSet.Fields[i].DisplayLabel;
    for j := 1 to r do
    begin
      for i := 0 to c - 1 do
        app.cells(j + 1, 1 + i) := DBGrid.DataSource.DataSet.Fields[i].AsString;
      DBGrid.DataSource.DataSet.Next;
    end;   
    ResultFileName := TempFileName;
    if ResultFileName = '' then
      ResultFileName := '数据导出';
    if FileExists(TempFileName) then
     DeleteFile(TempFileName);
    app.Activeworkbook.saveas(TempFileName);
    app.Activeworkbook.close(false);
    app.quit;
    app := unassigned;
end;
procedure TForm1.Button2Click(Sender: TObject);   //按钮保存
begin
try
    Screen.Cursor := crHourGlass;
    ExportDBGrid(DBGrid1, '导出数据');    //暂时将导出的文件名称为“导出数据”(的execl文件)   
finally
    Screen.Cursor := crDefault;
end;
end;

相关阅读 >>

Delphi xe6 在两个图片切换的时候实现翻书效果

Delphi控制摄像头

Delphi padl 处理字符串的函数

Delphi获取dll的函数列表

Delphi 从摄像头获取照片并转换为特定的格式

Delphi firedac连接mysql的时候报错

Delphi中引用sqlite3

Delphi setpriorityclass 设置当前程序的优先级

firemonkey 做 app 的界面设计方法研究

Delphi md5加密字符串

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...