PHP and COM - The Number Game (
Page 3 of 9 )
PHP's COM extension makes it easy
to access and manipulate COM objects that have been registered on your system.
One of these objects is the Excel.Application object, which exposes a number of
methods and properties that can be creatively used by an imaginative
developer.
The first step to using a COM object in your PHP script
involves creating an instance of the COM class; to quote the PHP manual, this
class provides you with "...a framework to integrate COM into your PHP scripts".
<?php
// create an object instance
$excel = new COM("Excel.Application") or die("Excel could not be
started");
?>
The argument passed to the class constructor is the name of
the component to be used. In this case, since I want an instance of Microsoft
Excel, I've used the Excel.Application object (more information on this object
can be obtained at
http://msdn.microsoft.com/library/en-us/modcore/html/deovrworkingwithmicrosoftexcelobjects.asp)
By
default, PHP assumes that the component is available on the local server. In the
event that you would like the component to be fetched from a remote DCOM server,
the server name can be specified as a second, optional argument to the
constructor. Note, however, that in order for this to work, the PHP
configuration variable
com.allow_dcom = true
must be set, either in the PHP configuration file or via the
ini_set() function call.
Once an object instance has been created, object
methods and properties can be accessed using standard OO conventions.
<?php
// pop open the Excel application
$excel->Visible = 1;
// turn off alerts
$excel->DisplayAlerts = 0;
// add a workbook
$excel->Workbooks->Add();
// save
$excel->Workbooks[1]->SaveAs("C:\\Inventory.xls");
// close the application
$excel->Quit();
?>
Since the Excel.Application object exposes a number of
different methods and properties, you can use it to create workbooks, add sheets
to the workbook, add or delete content to the cells of the worksheet, apply
formulae to the cells, save the workbook to the disk...in fact, everything that
you would be able to do with the application itself.
Keeping this in
mind, the example above is fairly simplistic - all it does is create an Excel
workbook and save it as a file - but it nevertheless demonstrates how easy it is
to do something that, in theory at least, sounds very difficult ("hey Matt, any
idea how to create an Excel spreadsheet in Windows using just
PHP?").