国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

使用PHPWord生成word文檔的方法詳解

2024-05-05 00:09:30
字體:
來源:轉載
供稿:網友

本文實例講述了使用PHPWord生成word文檔的方法。分享給大家供大家參考,具體如下:

有時我們需要把網頁內容保存為Word文檔格式,以供其他人員查看和編輯。PHPWord是一個用純PHP編寫的庫,使用PHPWord可以輕松處理word文檔內容,生成你想要的word文檔。

下載源碼

安裝

我們使用Composer 來安裝PHPWord。

composer require phpoffice/phpword

如何使用

自動加載

安裝好phpword后,新建一個php文檔,引入autoload.php。

require 'vendor/autoload.php';

實例化

實例化并新增一個空白頁。

$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。圖片源也可以是遠程圖片。

$section->addImage('logo.png', array('width'=>64, 'height'=>64));

頁眉

為Word文檔添加頁眉。

$header = $section->addHeader();$header->addText('Subsequent pages in Section 1 will Have this!');

頁腳

為word文檔添加頁腳,頁腳內容是頁碼,格式居中。

$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文檔

如果你想生成word文檔放在服務器上,可以使用:

$objWriter = /PhpOffice/PhpWord/IOFactory::createWriter($phpWord, 'Word2007');$objWriter->save('hellwoeba.docx');

下載Word文檔

如果你想直接下載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/.


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 无棣县| 望奎县| 仪陇县| 长乐市| 鲁甸县| 顺平县| 仪征市| 广南县| 荔波县| 商河县| 湖南省| 尉氏县| 金门县| 北川| 漳浦县| 喀什市| 诸城市| 永平县| 彭泽县| 岳普湖县| 陈巴尔虎旗| 铜川市| 新邵县| 湄潭县| 池州市| 新蔡县| 吴旗县| 平果县| 宝鸡市| 华容县| 德惠市| 大城县| 武功县| SHOW| 新乡市| 唐海县| 淮南市| 凌云县| 寻甸| 文化| 宣化县|