先在Project->Import Type Library->Microsoft Office引用
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Excel2000, Office_TLB, StdCtrls, OleServer;
type
TForm1 = class(TForm)
ExcelApplication1: TExcelApplication;
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
ExcelWorkbook1: TExcelWorkbook;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function FSize(FileName: string): LongInt;
//函数获得文件字节
var
F: File;
begin
AssignFile(F, FileName);
reset(F,1);
Result := FileSize(F);
CloseFile(F);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.Filter:='Excel File(*.XLS)|*.XLS';
if not OpenDialog1.Execute then
exit;
Memo1.Lines.Clear;
Memo1.Visible :=True;
Memo1.Lines.Text:='FileName: '+OpenDialog1.FileName;
Memo1.Lines.Add('Size: '+IntToStr(Fsize(OpenDialog1.FileName)));
//打开Excel
ExcelApplication1.Connect;
//显示当前窗口:
ExcelApplication1.Visible[0]:=True;
//更改 Excel 标题栏:
ExcelApplication1.Caption := '应用程序调用 Microsoft Excel';
//从文件对话框路径打开文件
ExcelWorkBook1.ConnectTo(ExcelApplication1.Workbooks.Open(OpenDialog1.FileName,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,
EmptyParam,
EmptyParam,
EmptyParam,
0));
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
ExcelApplication1.Disconnect;
ExcelApplication1.Quit;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
//添加自定义工具栏
ExcelApplication1.CommandBars.Add('KC定义的工具栏',1,False,False).Set_Visible(True);
//在自定义工具栏内添加按钮
with ExcelApplication1.CommandBars.Item['KC定义的工具栏'].Controls.Add(msoControlButton,
EmptyParam, EmptyParam, EmptyParam, EmptyParam)do
begin
Set_Caption('我的按钮');
Set_TooltipText('KC组的自定义按钮');
Set_OnAction('') ;
Set_Visible(True) ;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Close;
Application.Terminate;
end;
end.