PHP COM() Access to Microsoft Word

Friday, December 11 2009 @ 04:48 CST

Contributed by: justin carlson

In this article you will find very basic sample code for accessing Microsoft Word using PHP and COM(). This sample includes a table and some alignment settings.


<?php

/**
 * This example uses COM() to Word and Create a Table
 * Requires Windows, Microsoft Word
 *
 * @author justin DOT carlson AT gmail DOT com
 * @license none/free - sample code
**/

// dummy var
$total = 0;

// start instance
$word = new COM("Word.Application");
$word->Visible = True;
$document = $word->Documents->Add();

// start a new paragraph at the end of the document
$new_para = $document->Content->Paragraphs->Add($document->Bookmarks("\endofdoc")->Range);
$new_para->Range->Font->Size = 18;
$new_para->Range->Bold = True;
$new_para->Range->Text = "Example 1";
$new_para->Range->InsertParagraphAfter();

// add a new table at the end of the document
$range = $document->Bookmarks("\endofdoc")->Range;
$range->Tables->Add($range, 1, 2); // 1 row, 2 cells
$table = $document->Tables(1); //get first table in document


// add heading cells
$table->Cell(1, 1)->Range->Text = "Column A";
$table->Cell(1, 2)->Range->Text = "Column B";

// start at row 2, add some more row
for ($row = 2; $row < 12; $row ++) {
   
    $table->Rows->Add();
    $table->Cell($row, 1)->Range->Text = 'Item';
    $table->Cell($row, 2)->Range->Text = rand(10000, 99999);
    $total += ( int ) $table->Cell($row, 2)->Range->Text;

}

// apply some basic formatting
$table->AutoFormat(3);

// add a totals row
$table->Rows->Add();

$table->Cell($row, 1)->Range->ParagraphFormat->Alignment = 2; // right alignment (3 would be center)
$table->Cell($row, 1)->Range->Bold = True; // bold
$table->Cell($row, 1)->Range->Text = 'Total:';
$table->Cell($row, 2)->Range->Text = $total;

// want to save it?
$document->SaveAs("C:\path\to\file.doc');
$word->Quit();

?>

Comments (0)


tehuber.com
http://www.tehuber.com/article.php?story=20091211164830417