Author: William Gerbert
Delphi controls MS Office applications
Answer:
How can you remote control MS Office applications from your Delphi application? The
Answer is to use a TOLEContainer.
It requires some interface knowledge to use the right object(s) and their
properties. Some samples are added to Delphi demos, but all of them are targeted at
MSWord. I have posted examples for Internet Explorer elsewhere and here is a sample
for MSExcel:
1 // procedure is activated when OleOject activates user interface2 // procedure copies TStringGrid content to an (OleObject) Excel sheet3 4 procedure TForm1.OleContainer1Activate(Sender: TObject);
5 var6 ExcelSheet: Variant;
7 Count,
8 Curent: Variant;
9 i,
10 j: Integer;
11 begin12 // first we read how many sheets are open in a specified Excel document13 Count := OleContainer1.OleObject.Application.Sheets.Count;
14 15 // then we read the number of a sheet to witch user wants to add StringGrid 16 content
17 Curent := StrToInt(OKBottomDlg.Edit2.Text);
18 19 if Curent <> 0 then20 begin21 if Curent <= Count then22 // if the sheet with index Curent exist then copy content23 begin24 // first we activate the desiered sheet object25 OleContainer1.OleObject.Application.Sheets[Count].Activate;
26 // pass the object to a variant variable27 ExcelSheet := OleContainer1.OleObject.Application.ActiveSheet;
28 29 // now we can do what ever we like with it30 ExcelSheet.name := OKBottomDlg.Edit3.Text + IntToStr(Count);
31 for i := 0 to StringGrid1.RowCount do32 begin33 for j := 0 to StringGrid1.ColCount do34 begin35 ExcelSheet.Cells(i, j) := StringGrid1.Cells[j, i]
36 end37 end;
38 // here we copy the content39 end40 else// else if the sheet we are trying to access doesn't exsist41 begin42 // we add new sheets untill the requested43 // user's index is reached ( curent variable )44 for i := Count + 1 to Curent do45 begin46 OleContainer1.OleObject.Application.Sheets.Add
47 end;
48 // again we do as above49 OleContainer1.OleObject.Application.Sheets[Curent].Activate;
50 ExcelSheet := OleContainer1.OleObject.Application.ActiveSheet;
51 ExcelSheet.name := OKBottomDlg.Edit3.Text + IntToStr(Count);
52 for i := 0 to StringGrid1.RowCount do53 begin54 for j := 0 to StringGrid1.ColCount do55 begin56 ExcelSheet.Cells(i, j) := StringGrid1.Cells[j, i]
57 end58 end;
59 end60 end;
61 end;