溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用PHPWord生成word文檔

發(fā)布時間:2021-05-17 16:58:09 來源:億速云 閱讀:370 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)如何使用PHPWord生成word文檔,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

安裝

我們使用Composer 來安裝PHPWord。

composer require phpoffice/phpword

如何使用

自動加載

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

require 'vendor/autoload.php';

實例化

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

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();

添加文字內(nèi)容

向空白頁添加文字內(nèi)容,可以設(shè)置文字的樣式,包括字體、顏色、字號、粗體等等。

$fontStyle = [
  'name' => 'Microsoft Yahei UI',
  'size' => 20,
  'color' => '#ff6600',
  'bold' => true
];
$textrun = $section->addTextRun();
$textrun->addText('你好,這是生成的Word文檔。 ', $fontStyle);

鏈接

可以為Word文檔中的文字添加用于點擊跳轉(zhuǎn)的鏈接。

$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文檔添加頁腳,頁腳內(nèi)容是頁碼,格式居中。

$footer = $section->addFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', null, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER));

增加一頁

繼續(xù)增加一頁,加入內(nèi)容。

$section = $phpWord->addSection();
$section->addText('新的一頁.');

表格

增加一個基礎(chǔ)表格,可以設(shè)置表格的樣式。

$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文檔放在服務(wù)器上,可以使用:

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

下載Word文檔

如果你想直接下載Word文檔,不在服務(wù)器上保存的話,可以使用:

$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");

關(guān)于如何使用PHPWord生成word文檔就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI