uses
Excel2000, Math, OleServer
添加 ToolBar1, Gauge1,ImageList1,ExcelWorkbook1,ExcelWorksheet1,ADOConnection1,ADOQuery1,DataSource1 ,Memo1,DBGrid1,StatusBar1
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, ToolWin, DB, Grids, DBGrids, ADODB, StdCtrls,
Gauges, Excel2000, Math, OleServer;
type
TForm1 = class(TForm)
Memo1: TMemo;
ADOConnection1: TADOConnection;
ADOQuery1: TADOQuery;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
ToolBar1: TToolBar;
ImageList1: TImageList;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
Gauge1: TGauge;
ExcelWorksheet1: TExcelWorksheet;
StatusBar1: TStatusBar;
ExcelWorkbook1: TExcelWorkbook;
procedure ToolButton5Click(Sender: TObject);
procedure ToolButton7Click(Sender: TObject);
//procedure ExcelApplication1NewWorkbook(Sender: TObject;
// var Wb: OleVariant);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ToolButton5Click(Sender: TObject);
var
SQLStr : String;
begin //根据Memo1中的SQL语句提取数据库的信息显示在DBgrid
SQLStr := '';
SQLStr :=Memo1.Lines.GetText;
ADOQuery1.Close;
ADOQuery1.Sql.Clear;
ADOQuery1.SqL.Add(SQLStr);
ADOQuery1.Open;
end;
procedure TForm1.ToolButton7Click(Sender: TObject);
var
ExcelApp1:TExcelApplication; //uses Excel2000
Row,i:Integer;
AFileName : string;
begin
AFileName := 'D:\a.xlsx';
ExcelApp1:=TExcelApplication.Create(nil);
try
ExcelApp1.Connect;//和Execl连接如果没有Excel程序可能要出错
ExcelApp1.Workbooks.Add(Null,0);//为Excel添加工作薄
ExcelWorkbook1.ConnectTo(ExcelApp1.Workbooks[1]);
ExcelWorkSheet1.ConnectTo(ExcelWorkBook1.Sheets[1] as _WorkSheet);
if DBGrid1.DataSource.DataSet.RecordCount=0 then Exit;
row:=2;
for i:=1 to ADOQuery1.Fields.Count do
begin
ExcelWorkSheet1.Cells.Item[1,i]:=ADOQuery1.Fields[i-1].FieldName ;
end;
ADOQuery1.First;
while not ADOQuery1.Eof do
begin
Application.ProcessMessages;
for i:=1 to ADOQuery1.Fields.Count do
begin //把查询结果写入到电子表格中
excelworksheet1.Cells.Item[row,i].numberformatlocal:='@';
ExcelWorkSheet1.Cells.Item[row,i]:=ADOQuery1.Fields[i-1].Value;
end;
row:=row+1;
Gauge1.Progress:=Ceil(100*(row-2)/(ADOQuery1.RecordCount));
if Gauge1.Progress=100 then StatusBar1.Panels[1].Text:='导出完成,已保存至'+AFileName; //AFileName是导出文件存放的目录位置。
ADOQuery1.Next;
end;
finally
ExcelWorkBook1.SaveCopyAs(AFileName);
ExcelWorkSheet1.Disconnect;
ExcelWorkBook1.Close(False);
ExcelApp1.Disconnect;
ExcelApp1.Quit;
ExcelApp1.Free;
Gauge1.Visible:=False;
end;
end;
end.
浙公网安备 33010602011771号