Delphi simplifies the use of Microsoft Office applications by preinstalling some ready-to-use components that wrap the Automation interface of these servers. These components, available in the Servers page of the Palette, have been installed using the same technique I demonstrated in the last section.
What I want to underline here is that the real plus of Delphi lies in this technique of creating components to wrap existing Automation servers, rather than in the availability of some predefined server components.
Technically, it is possible to use variants to interact with Automation servers, as we've seen in the section "Introducing Type Libraries." Using interfaces and the type libraries is certainly better, because the compiler helps you catch errors in the source code and produces faster code. Thanks to the new server component, this process is also quite straightforward.
I've written a program, called DBOffice, which uses predefined server components to send a table to Word and to Excel. In both cases, you can use the application object, the document/ worksheet object, or a combination of the two. There are other specialized components, for tasks such as handling Excel charts, but this example will suffice to introduce use of the built-in Office components.
The DBOffice program was tested with Office 97. I'm currently using StarOffice more often than the Microsoft suite, so I never feel compelled to give Microsoft more money by upgrading to their newer offerings.
In case of Microsoft Word, I use only a document object with default settings. The code used to send the table to Word starts by adding some text to a document:
This code follows the typical while loop, which scans the database table and has the following code inside:
while not Table1.EOF do begin
The final part of the code gets a little more complex. It works on a selection and on a row of the table, respectively stored in two variables of the Range and Row types defined by Word and available in the Word97 unit (the program will have to be updated if you choose the Office 2000 version of the server component while installing Delphi).
procedure TFormOff.BtnWordClick(Sender: TObject); var
Row1: Word97.Row; begin
RangeW := WordDocument1.Content;
Row1.ConvertToText (ov1); end;
As you can see in the last statement above, in order to pass a parameter, you must first save it in an OleVariant variable, because many parameters are passed by reference, so you cannot pass a constant value. This implies that if there are many parameters, you must still define some, even if you are fine with the default values. An often-useful alternative is to use a temporarily variant variable and apply the method to it, because variants don't require strict type-checking on the parameters. This technique is used in the code above to call the ConvertToTable method, which has more than 10 parameters.
Was this article helpful?