Jaslabs: High performance Software

High Performance Software

How to create Microsoft Office Documents with PHP

By Justin Silverton

There are two main ways to build Excel, Word, and PowerPoint documents using PHP. The first is by using the COM library (only if you are using a Windows server) and the other is by using a more standardized approach such as HTML or CSV.


Dynamically creating a word document:

<?php
$word = new COM("word.application");

$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '2"';
$word->Selection->PageSetup->RightMargin = '2"';

//Setup the font
$word->Selection->Font->Name = 'Verdana';
$word->Selection->Font->Size = 8;

//Write some text
$word->Selection->TypeText("This is a test document");
//Save the document as DOC file
$word->Documents[1]->SaveAs("c:\\docs\\test1.doc");

//quit and release COM resources
$word->quit();
$word->Release();
$word = null;

?>

Dynamically creating an excel document

<?php
$excel = new COM("excel.application");
$excel->Visible = 0;

//Create a new workbook
$wkb = $excel->Workbooks->Add();
$sheet = $wkb->Worksheets(1);

//This code adds the text 'myvalue' on row 2, column 4
$sheet->activate;
$cell = $sheet->Cells(2,4);
$cell->Activate;
$cell->value = 'myvalue';

$wkb->SaveAs("C:\docs\test.xls");

//close and free resources
$wkb->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
?>

Dynamically creating a powerpoint presentation

<?php
$powerpnt = new COM("powerpoint.application");
//Creating a new presentation
$pres=$powerpnt->Presentations->Add();
//Adds the first slide. "12" means blank slide
$pres->Slides->Add(1,12);
//Adds another slide. "10" means a slide with a clipart and text
$pres->Slides->Add(2,10);
//Adds a textbox
$pres->Slides[1]->Shapes->AddTextbox(1,20,50,300,40);
//Save the document as PPT file
$powerpnt->Presentations[1]->SaveAs("C:\Docs\test1.ppt");

//free resources and quit powerpoint
$powerpnt->quit();
?>

How to find Word, Excel, and Powerpoint functions

The following will show you all of the functions that are possible when accessing Microsoft Office components through php:

  1. Open Microsoft Word, Excel, or Powerpoint
  2. Press Alt+F11 to start the Visual Basic Editor
  3. Press F2
  4. Find “ThisDocument” on the left. In the right frame you’ll see the available variables and functions that can be used with the COM object.
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati

23 Comments so far

  1. […] From the JSLabs blog today, there’s a quick illustration of how to dynamically create three different types of Microsoft Office files - a Word document, Powerpoint and an Excel file. There are two main ways to build Excel, Word, and PowerPoint documents using PHP. The first is by using the COM library (only if you are using a Windows server) and the other is by using a more standardized approach such as HTML or CSV. […]

  2. Cesar D. Rodas July 2nd, 2007 5:09 pm

    And what about is I am using Linux?

  3. blockdog July 3rd, 2007 3:20 am
  4. PHP и MS OFFICE : 2.0 July 3rd, 2007 8:38 am

    […] Всю статью можно читать на сайте автора. […]

  5. Alexey Ovchinnikov July 6th, 2007 1:41 am

    There is some bug in a code that presented above. After creating an COM object and saving some word document as file c:\\docs\\test1.doc, COM object not released from the memory. Not clear how to correct this bug ?

  6. Denis July 7th, 2007 4:07 am

    For creating Word documents, you can also use rtf format. There is free library for creating rtf with php- http://www.phprtf.com.

  7. vlad July 8th, 2007 11:37 am

    There is some bug in a code that presented above. After creating an COM object and saving some word document as file c:\\docs\\test1.doc, COM object not released from the memory. Not clear how to correct this bug ?

    HOW ?????????

  8. Justin Silverton July 8th, 2007 3:10 pm

    What version of PHP are you using?

  9. […] Justin Silverton describe dos formas principales de construir un documento de Excel, Word y PowerPoint usando PHP. La primera es usar la librería COM (sólo es válido si estas usando un servidor Windows), la segunda forma es utilizar una solución más estándar basada en HTML o CSV. […]

  10. James July 13th, 2007 6:40 am

    How can i open an existing excel file?
    somehow find a lsit of all methods of the class?

  11. Dmitry July 14th, 2007 8:05 am

    You can also use XML formats for MS Office documents

  12. Billy July 21st, 2007 12:01 am

    I tried to create a ppt on the fly; copied and pasted but got an error:

    Fatal error: Uncaught exception ‘com_exception’ with message ‘Failed to create COM object `powerpoint.application’:Access is denied. ‘

    Figured it was an IE security issue; tweaked all applicable security settings to no avail. Any idea how to solve?

  13. Justin Silverton July 21st, 2007 12:51 am

    Billy,

    your web server may not have the proper permissions to create the new document through COM. You might want to try checking the directory permissons (through the security tab of the properties).

  14. Deep July 24th, 2007 6:02 am

    I tried to create a word document and got the following error.

    Fatal error: Uncaught exception ‘com_exception’ with message ‘Source: Microsoft Word
    Description: Could not open macro storage.’

    The error seems to be generating because the IUSR_MACHINENAME has no privileges to automate MS-Word. I have been looking around a lot to overcome this. But no success so far. :(

    Please Help!

  15. Pankaj July 26th, 2007 9:00 am

    Hey Dmitry,

    How we can we use XML to create doc ? Please provide some referance if you have.

  16. Grugs August 2nd, 2007 12:43 pm

    Cesar D. Rodas asked “And what about is I am using Linux?” The answer was “Use PEAR… For example, Excel: http://pear.php.net/package/Spreadsheet_Excel_Writer”

    Could you please give an example for Word?

    And I’d like to second the request:

    How we can we use XML to create doc? Please provide some references if you have any. - Thanks.

    My web host does not seem to support the “COM” class; I just get “Fatal error: Class ‘COM’ not found”.

  17. Justin Silverton August 2nd, 2007 10:15 pm

    Grugs,

    I did some research and found some Office/XML examples for you (and anyone else that is interested):

    office 2007 spreadsheetXML classes:

    http://blogs.balliauw.be/blogs/maarten/archive/2006/12/14/office-2007-spreadsheetml-classes-in-php.aspx

  18. Ronald August 28th, 2007 1:53 am

    Could you give me some examples of PHP script about using TabStob class for Ms.Word? Thank you for your help.

  19. Ajmaltash August 31st, 2007 7:03 am

    in iis for windows put windows authenticated user on.

  20. R Mike September 5th, 2007 5:45 am

    Hi,

    I am using PHP5.0 with IIS and tried to run an example program you provided above but nothing happen. ( even error message does not appear on the browser(IE 6.0).

    The setting of php.ini is almost as original copied from php.ini-recommended, So do I need to change some?

    Thank you for your supports,

  21. lellomel September 6th, 2007 10:59 am

    Hi,
    I have this error while attempting to save word document: Fatal error: Call to undefined method variant::SaveAs()
    Can you help me?
    Thanks in advance!

  22. Sam September 12th, 2007 12:22 pm

    How can you open an existing PPT file and delete a slide and then save the modified PPT file as a new presentation?

  23. rajesh February 29th, 2008 10:07 am

    i have bugs in creating doc using php after running the program there must be a fatal error in it. please give solution for this problem

Leave a reply