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 declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
eclApp,WorkBook:Variant;
//聲明為OLE Automation 對象
xlsFileName:string;begin
xlsFileName:=‘ex.xls‘;
try
//創建OLE對象Excel Application與 WorkBook
eclApp:=CreateOleObject(‘Excel.Application‘);
WorkBook:=CreateOleobject(‘Excel.Sheet‘);
except
ShowMessage(‘您的機器裡未安裝Microsoft Excel。‘);
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(2 , 1):=‘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.
經過上述操作過程後,我們就可以很放心地將數據庫中的數據轉換成Excel文件了。