O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #49. Create Excel Spreadsheets Dynamically

Use the new XML format supported by Microsoft Office 2004 to generate spreadsheets dynamically.

Word processing documents aren't the only things you might want to generate dynamically [Hack #48] . You also can create spreadsheets dynamically. With the new XML features of Microsoft Office 2004, we can build spreadsheets by simply using XML.

Start by creating a document in Excel, as shown in Figure 5-24.

Use the Save As command to save the spreadsheet in XML format. Then use the XML that's exported by Excel as the basis of your PHP file.

The Code

Save the code in Example 5-40 as spreadsheet.php.

The simple Excel spreadsheet that I use as a template

Figure 5-24. The simple Excel spreadsheet that I use as a template

Example 5-40. Using state data to represent a spreadsheet

<?
header( "content-type: text/xml" ); $data = array( array(state => "Alabama", population => 4530182 ), array(state => "Alaska", population => 655435 ), array(state => "Arizona", population => 5743834 ), array(state => "Arkansas", population => 2752629 ), array(state => "California", population => 35893799 ), … array(state => "Washington", population => 6203788 ), array(state => "West Virginia", population => 1815354 ), array(state => "Wisconsin", population => 5509026 ), array(state => "Wyoming", population => 506529 ) ); echo( "<?xml version=\"1.0\"?>\n" ); echo( "<?mso-application progid=\"Excel.Sheet\"?>\n" ); ?> <Workbook ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required