ITPub博客

首页 > Linux操作系统 > Linux操作系统 > DELPHI7 DBGRID 导出EXCEL

DELPHI7 DBGRID 导出EXCEL

原创 Linux操作系统 作者:zaorv 时间:2019-01-21 22:33:04 0 删除 编辑

uses comobj;


function TSocialInsuranceForm.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
app.activeSheet.Columns[3].numberformatlocal:='@'; // 设置第三列为文本格式
// app.activesheet.rows[2].numberformat:='@'; //设置第二行为文本格式
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 TsocialInsuranceForm.ExportBtnClick(Sender: TObject);
begin //导出按钮

try
Screen.Cursor := crHourGlass;
ExportDBGrid(SocialInsuranceDbg, '导出数据.xls'); //暂时将导出的文件名称为“导出数据.xls”(的execl文件)
application.MessageBox('导出数据完成','提示',0+64);
finally
Screen.Cursor := crDefault;
end;

end;


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/729024/viewspace-564891/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-09-12

  • 博文量
    192
  • 访问量
    147272