📜 ⬆️ ⬇️

How to create Microsoft Office documents using PHP

There are two main ways to build Excel, Word, and PowerPoint using PHP. The first is using the COM library (only under Windows server) and the other using more standardized formats such as CSV and HTML.

Dynamic Word Document Creation:


<?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;

?>


Dynamic creation of 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();
?>

Dynamic 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 features


The text further tells how to find functions for working with Microsoft Office components from under 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 will see the possible variables and functions that can be used for the COM object.


')

Source: https://habr.com/ru/post/31149/


All Articles