Delphi+DBGrid导出Excel

时间:2023-11-09 20:54:44

uses ComObj;

//DBGrid:指定的DBGrid;SaveFileName:要保存的文件名

function ExportDBGrid(DBGrid: TDBGrid; SaveFileName: string): boolean; 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:=SaveFileName;

if SaveDialog1.Execute then

TempFileName := SaveDialog1.FileName

else

Exit;

app.Workbooks.add;

app.Visible := false;

Screen.Cursor := crHourGlass;

DBGrid1.DataSource.DataSet.First;

c:=DBGrid1.DataSource.DataSet.FieldCount;

r:=DBGrid1.DataSource.DataSet.RecordCount;

Application.ProcessMessages;

for i:=0 to c-1 do

begin

app.ActiveSheet.Columns[i+1].ColumnWidth:=15;//设置格宽度

app.cells(1,1+i):=DBGrid1.DataSource.DataSet.Fields[i].DisplayLabel;

end;

for j := 1 to r do

begin

for i := 0 to c - 1 do

begin

app.cells[j+1,1].numberformatlocal:='@';//设置成文本

app.cells(j+1,1+i):=DBGrid1.DataSource.DataSet.Fields[i].AsString; end;

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;