Delphi 3 - Delphi and Microsoft Office - Automating Excel 3
Delphi 3 - Delphi and Microsoft Office - Automating Excel 3
1 of 4
EMBARCADERO HOME
http://edn.embarcadero.com/article/10128
COMMUNITIES
ARTICLES
BLOGS
RESOURCES
DOWNLOADS
HELP
EDN Delphi
RATING
Download Trial
Buy Now
Delphi on
Facebook
Like
7,568 people like Delphi.
Luiz
Khaled
var
Form1: TForm1;
implementation
uses
ComObj, XLConst;
{$R *.DFM}
procedure TForm1.FormDestroy(Sender: TObject);
begin
if not VarIsEmpty(XLApp) then begin
XLApp.DisplayAlerts := False; // Discard unsaved files....
XLApp.Quit;
end;
25.10.2012 17:38
Delphi 3 - Delphi and Microsoft Office: Automating Excel and Word - ...
2 of 4
http://edn.embarcadero.com/article/10128
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
XLApp:= CreateOleObject('Excel.Application');
XLApp.Visible := True;
XLApp.Workbooks.Add(xlWBatWorkSheet);
XLApp.Workbooks[1].WorkSheets[1].Name := 'Delphi Data';
InsertData;
HandleRange;
ChangeColumns;
end;
procedure TForm1.InsertData;
var
i: Integer;
Sheet: Variant;
begin
Sheet := XLApp.Workbooks[1].WorkSheets['Delphi Data'];
for i := 1 to 10 do
Sheet.Cells[i, 1] := i;
Sheet.Cells[i, 1] := '=Sum(A1:A10)';
end;
procedure TForm1.HandleRange;
var
Range: Variant;
begin
Range :=
XLApp.Workbooks[1].WorkSheets['Delphi Data'].Range['C1:F25'];
Range.Formula := '=RAND()';
Range.Columns.Interior.ColorIndex := 3;
Range.Borders.LineStyle := xlContinuous;
end;
procedure TForm1.ChangeColumns;
var
ColumnRange: Variant;
begin
ColumnRange := XLApp.Workbooks[1].WorkSheets['Delphi Data'].Columns;
ColumnRange.Columns[1].ColumnWidth := 5;
ColumnRange.Columns[1].Font.Bold := True;
ColumnRange.Columns[1].Font.Color := clBlue;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Sheet: Variant;
Num: Integer;
begin
Sheet := XLApp.Workbooks[1].WorkSheets['Delphi Data'];
Num := Sheet.Range['C1:F25'].Columns.Interior.PatternColor;
ShowMessage(Format('Value: %x', [Num]));
end;
end.
As I implied above, it is easy to actually insert data in a spreadsheet. In fact, the technique involved
is very similar to what you would use putting data into a TStringGrid control in Delphi.
To get started, open up Excel and create a new spreadsheet:
procedure TForm1.Button1Click(Sender: TObject);
begin
XLApp:= CreateOleObject('Excel.Application');
XLApp.Visible := True;
XLApp.Workbooks.Add(xlWBatWorkSheet);
XLApp.Workbooks[1].WorkSheets[1].Name := 'Delphi Data';
InsertData;
HandleRange;
ChangeColumns;
end;
As you can, see, I create a single workbook with one worksheet in it. The code then names the
worksheet Delphi Data. The InsertData, HandleRange and ChangeColumns calls are custom Delphi
routines which I will now proceed to describe.
To insert data into the spreadsheet, execute the following function:
procedure TForm1.InsertData;
var
i: Integer;
Sheet: Variant;
begin
Sheet := XLApp.Workbooks[1].WorkSheets['Delphi Data'];
for i := 1 to 10 do
Sheet.Cells[i, 1] := i;
Sheet.Cells[i, 1] := '=Sum(A1:A10)';
end;
The method starts by retrieving a pointer to the worksheet you want to manipulate. As you know, this
pointer is an instance of IDispatch that is stored inside a variant. You don't need to know anything
about how IDispatch works in order to call the methods of this object.
The code proceeds to insert ten integers into the sheet. The Cells property works exactly as you
would expect, except Excel puts the Row first and the Column second.
After inserting the numbers in the worksheet, the final stage is to insert a formula and add up the
column of numbers. To do this, you simply insert the formula much as you would if you were in Excel
itself. In particular, you store the formula in string, and then insert it into the appropriate cell:
Sheet.Cells[i, 1] := '=Sum(A1:A10)';
25.10.2012 17:38
Delphi 3 - Delphi and Microsoft Office: Automating Excel and Word - ...
3 of 4
http://edn.embarcadero.com/article/10128
Sometimes you might want to perform an operation on a range of data in the spreadsheet. To do this,
you use the Excel Range object:
Sheet.Range['C1:F25'].Formula := '=RAND()';
This code could be inserted into the bottom of the InsertData method. It fills all the cells between C1
and F25 with random numbers between 0 and 1.
One of the key objects in both Excel and Word is the Range object. It allows you to work with a range
of cells or columns at one time. In either Word or Excel, you generally enter or read data by using the
Range object. In short, if you want to insert text into a Word document, then you will generally use
the Range object!
BEGIN NOTE:
With Word, it is also possible to insert data via a considerably simpler method. For instance, the
following procedure will enter data at the current insertion point into a currently open document in
Microsoft Word:
procedure TForm1.Button1Click(Sender: TObject);
var
V: Variant;
begin
V := GetActiveOleObject('Word.Basic');
V.Insert('Sam');
end;
In this case, I have chosen not to open a new version of Word, but instead call GetActiveOleObject to
get a handle to a document in an instance of Word that is already running. This kind of technology is
very easy to use, and is perfect for some projects. It does not, however, have the power of the
technology I am showing you in this paper.
END NOTE
To access a Range object in Excel, simply specify the Range with which you want to work:
Range := Sheet.Range['C1:F25'];
In this case the code defines a range from cell C1 to cell F25. Any operations performed on the
returned Range object will affect all the cells in that range.
Here is a simple function showing how to change the values and appearance of a range of cells:
procedure TForm1.HandleRange;
var
Range: Variant;
begin
Range :=
XLApp.Workbooks[1].WorkSheets['Delphi Data'].Range['C1:F25'];
Range.Formula := '=RAND()';
Range.Columns.Interior.ColorIndex := 3;
Range.Borders.LineStyle := xlContinuous;
end;
The first line of code returns a pointer to the range you want to manipulate. The second line fills all
the values in the range C1:F25 with random numbers between 0 and 1, as explained earlier.
The third line of code changes the color of the entire block of cells to red. You can use the Excel
online help to see the values in the ColorIndex, but the first few default values are as follows: black,
white, red, green, blue, yellow, purple, cyan. Red is the third item in the list, so setting the
ColorIndex to 3 makes the selected range of cells Red.
At the same time that you change the color, you also loose your borders. This is a peculiarity of Excel,
and it can be worked around by resetting the LineStyle of the selected cells as shown in the last line
of code in the procedure. Once again, when you are working with constants like this, you can find
them in the XLCONST.pas or EXCELTLB.pas files included with the example programs accompanying
this article, or can retrieve them from the type library as explained earlier.
For those who are interested, here is a line of code that changes the background of a range:
Range.Columns.Interior.Pattern := xlPatternCrissCross;
As you can see, when you want to work with the columns in a worksheet, you can access them from a
Range object. In particular, the Range object contains a collection of columns that you can access
using array notation.
To change the width of a column, use the ColumnWidth property, and to change the Font, use the
Font property. Going into much more detail would be pointless, as this code is easy to write.
LATEST COMMENTS
Move mouse over comment to see the full text
25.10.2012 17:38
Delphi 3 - Delphi and Microsoft Office: Automating Excel and Word - ...
4 of 4
http://edn.embarcadero.com/article/10128
Delphi 3 - Delphi and Microsoft Office: Automating Excel and Word - Page 3
Useful article, I'm using OLE to grab data from multiple excel '07 files in Delphi I'm trying
to figure out how to ignore cells which have an error eg #NAME? or #DIV/0 The VB syntax
given on...
Reply Posted by James Nelson on Sep 14 2004
Delphi 3 - Delphi and Microsoft Office: Automating Excel and Word - Page 3
At work the 'IT' team use VB and VBA for all MS Office 'automation' usually with those
lovely 'Runtime Error 1004' or such. I was writing a reporting application from a backend
DB using Delphi...
Server Response from: ETNASC02
Site Map
25.10.2012 17:38