unit Unit1;<br><br>interface<br><br>uses<br> Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br> Dialogs, DB, DBTables, Grids, DBGrids, Buttons,comobj;<br><br>type<br> TForm1 = class(TForm)<br> DBGrid1: TDBGrid;<br> Table1: TTable;<br> DataSource1: TDataSource;<br> SpeedButton1: TSpeedButton;<br> SpeedButton2: TSpeedButton;<br> SpeedButton3: TSpeedButton;<br> procedure SpeedButton1Click(Sender: TObject);<br> procedure SpeedButton2Click(Sender: TObject);<br> procedure SpeedButton3Click(Sender: TObject);<br> private<br> { Private declarations }<br> public<br> { Public declarations }<br> end;<br><br>var<br> Form1: TForm1;<br> varExcel:Variant;<br>implementation<br><br>{$R *.dfm}<br><br>procedure TForm1.SpeedButton1Click(Sender: TObject);//打开EXCEL<br><br>begin<br> varExcel:=Createoleobject('Excel.Application');<br> varExcel.Visible:=True;<br> if not varIsEmpty(varExcel)then<br> Begin<br> VarExcel.Workbooks.Add;<br> varExcel.Workbooks[1].Worksheets[1].name:='数据库';<br>// PrintBtn.enabled:=True;<br> Application.BringToFront;<br> end;<br>// except<br>// showmessage('找不到Microsoft Excel');<br>// end;<br>end;<br><br>procedure TForm1.SpeedButton2Click(Sender: TObject);//导出数据<br>Var<br> i,j:integer;<br> bookmark:Tbookmark;<br>begin<br> table1.DisableControls;<br> Begin<br> For i:=0 to table1.FieldCount-1 do<br> varExcel.workbooks[1].worksheets[1].cells[1,i+1].value:=table1.fields.Displaylabel;<br> end;<br> try<br> bookmark:=table1.GetBookmark;<br> try<br> table1.First;<br> j:=2;<br> while not table1.Eof do<br> Begin<br> For i:=0 to table1.fieldcount-1 do<br> Begin<br> varExcel.workbooks[1].worksheets[1].cells[j,i+1].value:=table1.fields.asstring;<br> end;<br> table1.Next;<br> j:=j+1;<br> end;<br> Finally<br> table1.GotoBookmark(bookmark);<br> table1.FreeBookmark(bookmark);<br> end;<br> finally<br> table1.EnableControls;<br> end;<br>end;<br><br>procedure TForm1.SpeedButton3Click(Sender: TObject);//关闭保存<br>begin<br> if not varIsEmpty(varExcel)then<br> Begin<br> varExcel.DisplayAlerts:=False;<br> varExcel.Quit;<br> end;<br>end;