有時咱們須要把網頁內容保存爲Word文檔格式,以供其餘人員查看和編輯。PHPWord是一個用純PHP編寫的庫,使用PHPWord能夠輕鬆處理word文檔內容,生成你想要的word文檔。php
咱們使用Composer來安裝PHPWord。html
composer require phpoffice/phpword
安裝好phpword後,新建一個php文檔,引入autoload.php。c++
require 'vendor/autoload.php';
實例化並新增一個空白頁。web
$phpWord = new \PhpOffice\PhpWord\PhpWord(); $section = $phpWord->addSection();
向空白頁添加文字內容,能夠設置文字的樣式,包括字體、顏色、字號、粗體等等。瀏覽器
$fontStyle = [ 'name' => 'Microsoft Yahei UI', 'size' => 20, 'color' => '#ff6600', 'bold' => true ]; $textrun = $section->addTextRun(); $textrun->addText('你好,這是生成的Word文檔。 ', $fontStyle); 連接
能夠爲Word文檔中的文字添加用於點擊跳轉的連接。服務器
$section->addLink('https://www.helloweba.net', '歡迎訪問Helloweba', array('color' => '0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE)); $section->addTextBreak();
能夠在word中添加圖片,如圖片地址logo.png,尺寸爲64x64。圖片源也能夠是遠程圖片。app
$section->addImage('logo.png', array('width'=>64, 'height'=>64));
爲Word文檔添加頁眉。composer
$header = $section->addHeader(); $header->addText('Subsequent pages in Section 1 will Have this!');
爲word文檔添加頁腳,頁腳內容是頁碼,格式居中。post
$footer = $section->addFooter(); $footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', null, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER));
繼續增長一頁,加入內容。字體
$section = $phpWord->addSection(); $section->addText('新的一頁.');
增長一個基礎表格,能夠設置表格的樣式。
$header = array('size' => 16, 'bold' => true); $rows = 10; $cols = 5; $section->addText('Basic table', $header); $table = $section->addTable(); for ($r = 1; $r <= 8; $r++) { $table->addRow(); for ($c = 1; $c <= 5; $c++) { $table->addCell(1750)->addText("Row {$r}, Cell {$c}"); } }
若是你想生成word文檔放在服務器上,能夠使用:
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('hellwoeba.docx');
若是你想直接下載Word文檔,不在服務器上保存的話,能夠使用:
$file = 'test.docx'; header("Content-Description: File Transfer"); header('Content-Disposition: attachment; filename="' . $file . '"'); header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Expires: 0'); $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $xmlWriter->save("php://output");
上述代碼會強制瀏覽器下載爲word文檔。
更多有關PHPWord的內容,請參考PHPWord文檔:http://phpword.readthedocs.org/.