Unit excel;
Interface
Uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComObj,
{ComObj是操作OLE对象的函数集}
Type
TForm1 = class(TForm)
Button1: TButton;
Procedure Button1Click(Sender: Tobject);
Private
{ Private declaration }
Public
{ Public declaration }
end;
var
Form1: TForm1;
Implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: Tobject);
var
eclApp, WordBook: Variant; { 声明为OLE Automation对象 }
xlsFileName: string;
begin
xlsFileName := 'ex.xls';
try
{ 创建OLE对象:Excel Application与WordBook }
eclApp := CreateOleObject('Excel.Application');
WorkBook := CreateOleObject('excel.Sheet');
Except
Application.MessageBox('你的机器没有安装Microsoft Excel', '使用Microsoft Excel',
MB_OK + MB_ICONWarning);
Exit;
End;
Try
ShowMessage('下面演示:新建一个XLS文件,并写入数据,并关闭它。');
WorkBook := eclApp.workbooks.Add;
eclApp.Cells(1, 1) := '字符型';
eclApp.Cells(2, 1) := 'Excel文件';
eclApp.Cells(1, 2) := 'Money';
eclApp.Cells(2, 2) := 10.01;
eclApp.Cells(1, 3) := '日期型';
eclApp.Cells(2, 3) := Date;
WorkBook.SaveAS(xlsFileName);
WorkBook.close;
ShowMessage('下面演示:打开刚创建的XLS文件,并修改其中的内容,然后,由用户决定是否保存。');
WorkBook := eclApp.workbooks.Open(xlsFileName);
eclApp.Cells(1, 4) := 'Excel文件类型';
If MessageDlg(xlsFileName + '已经被修改,是否保存?', mtConfirmation, [mbYes, mbNo], 0)
= mrYes then
WorkBook.Save
Else
WorkBook.Saved := True; { 放弃保存 }
WorkBook.close;
eclApp.Quit; // 退出Excel Application
{ 释放Variant变量 }
eclApp := Unassigned;
except
ShowMessage('不能正确操作Excel文件。可能是该文件已被其他程序打开,或系统错误。');
WorkBook.close;
eclApp.Quit;
{ 释放Variant变量 }
eclApp := Unassigned;
end;
end;
end.