利用Delphi 5中調用Excel 97
---- 在Delphi 5中簡單地封裝了一組Microsoft Office自動化對象(Automation servers)。它使得我們很容易地把Office中的應用程序(Word, Excel, PowerPoint, Outlook and Access等)當作一個com應用服務器進行控制。在Delphi 5中已經帶了Word與PowerPoint的例子,因為Excel的調用與這兩個應用服務器的調用略有不同,所以本人根據這兩個例子寫了個Excel 97的簡單例子以供參考。
---- 步聚
1. 創建一個普通Application。
2. 在Form中分別放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。
3. 連接Excel 97,具體方法如下:
打開Excel97。
Try
ExcelApplication1.Connect;
Except
End;
ExcelApplication1.Visible[0]:=True;
增加一個Workbook。
ExcelWorkbook1.ConnectTo(ExcelApplication1.
Workbooks.Add(EmptyParam,0));
添加一個Worksheet。
var
Temp_Worksheet: _WorkSheet;
begin
Try
Temp_Worksheet:=ExcelWorkbook1.
WorkSheets.Add(EmptyParam,
EmptyParam,EmptyParam,EmptyParam,0)
as _WorkSheet;//(注意)
ExcelWorkSheet1.ConnectTo(Temp_WorkSheet);
Except
ShowMessage(Failure);
End;
end;
關閉Excel.
Try
ExcelApplication1.Quit;
ExcelWorksheet1.Disconnect;
ExcelWorkbook1.Disconnect;
ExcelApplication1.Disconnect;
Except
End;
---- 4. 對Excel的一些操作:
選擇當前Workbook的某一Worksheet.
procedure TForm1.ComboBox1DropDown
(Sender: TObject);
var
i: Integer;
begin
ComboBox1.Clear;
For i:=1 to ExcelWorkbook1.
Worksheets.Count do
ComboBox1.Items.Add
((ExcelWorkbook1.Worksheets.Item[i]
as _WorkSheet).Name);
end;
procedure TForm1.ComboBox1Change
(Sender: TObject);
begin
ExcelWorkSheet1.ConnectTo
(ExcelWorkbook1.Worksheets.Item
[ComboBox1.ItemIndex+1] as _WorkSheet);
ExcelWorkSheet1.Activate;
end;
選擇某一Workbook:
procedure TForm1.ComboBox2DropDown
(Sender: TObject);
var
i: Integer;
begin
ComboBox2.Clear;
if ExcelApplication1.Workbooks.Count >0 then
For i:=1 to ExcelApplication1.Workbooks.Count do
Combobox2.Items.Add(ExcelApplication1.
Workbooks.Item[i].Name);
end;
procedure TForm1.ComboBox2Change(Sender: TObject);
begin
ExcelWorkSheet1.Disconnect;
ExcelWorkBook1.ConnectTo(ExcelApplication1.Workbooks.
Item[Combobox2.ItemIndex+1]);
ExcelWorkBook1.Activate;
ExcelWorksheet1.ConnectTo(ExcelWorkBook1.
ActiveSheet as _WorkSheet);
ExcelWorkSheet1.Activate;
end;
對某一單元格進行賦值及取值。
procedure TForm1.Button5Click(Sender: TObject);
begin
ExcelWorksheet1.Cells.Item[SpinEdit2.Value,
SpinEdit1.Value]:=Edit1.Text;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
Edit1.Text:=ExcelWorksheet1.Cells.Item[
SpinEdit2.Value,SpinEdit1.Value];
end;
選擇某一區域
ExcelWorkSheet1.Range[A1,C1].Select;
打開一個Excel文件。
if OpenDialog1.Execute then
Begin
Try
ExcelWorkBook1.ConnectTo
(ExcelApplication1.Workbooks.Open
(OpenDialog1.FileName,
EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,
EmptyParam,EmptyParam,0));
ExcelWorkSheet1.ConnectTo
(ExcelWorkBook1.Activesheet
as _Worksheet);
Except;
End;
End;
---- 說明
---- 本程序在Win98+Delphi 5+Excel 97下運行通過。本例子還可以作適當的擴充,如DDE、執行宏調用、保存文件、打印文件及對Excel的設置等,此設置方法請參閱Microsoft Excel Visual Basic參考中的Microsoft Excel對象。