使用phpword插件實現word文檔導出
- 2020 年 2 月 26 日
- 筆記
一:安裝phpword插件
composer require phpoffice/phpword
phpword的GitHub地址: https://github.com/PHPOffice/PHPWord
phpword文檔地址: https://phpword.readthedocs.io/en/latest/
二:phpword使用
phpword的使用十分簡單,根據github的教程即可實現,這裡我來講解一下生成word文檔的兩種方式
1:使用html模板生成word文檔
//html模板資訊 $html = '<div>111</div>' $phpWord = new PhpWord(); $section = $phpWord->addSection(); \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $filename = 'test.docx'; $objWriter->save($filename);
如上就可以將html模板資訊生成word文檔,如果你想要實現下載word文檔
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); header('Content-Disposition: attachment;filename="' . $title . '.docx"'); header('Cache-Control: max-age=0'); //html資訊 $html = '<div>111</div>' $phpWord = new PhpWord(); $section = $phpWord->addSection(); \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('php://output');2:使用word模板生成word文檔
(1)載入word模板
$templateProcessor = new TemplateProcessor('test.docx');(2)給word模板變數賦值
如給定一個模板:
模板資訊為:${name} 用戶:${username}給上面的模板的name和username變數賦值
$templateProcessor->setValue('name', 'word模板'); $templateProcessor->setValue('username', 'test');我們還可以同時給多個變數同時賦值
$templateProcessor->setValues([ 'name' => ''word模板, 'username' => 'test', ]);
(3):給變數賦值影像
如果想要將變數賦值為圖片,可以使用setImageValue方法來設置影像
$templateProcessor->setImageValue('img', 'logo.png');我們還可以給影像設置樣式
$templateProcessor->setImageValue('img', [ 'path' => 'logo.png', 'width' => 100, 'height' => 100, 'ratio' => false ]);(3)給模板循環數次
word模板如下:
${block_name} Customer: ${customer_name} Address: ${customer_address} ${/block_name}循環並賦值方法如下:
$replacements = array( array('customer_name' => 'Batman', 'customer_address' => 'Gotham City'), array('customer_name' => 'Superman', 'customer_address' => 'Metropolis'), ); $templateProcessor->cloneBlock('block_name', 0, true, false, $replacements);這時候生成的結果如下:
Customer: Batman Address: Gotham City Customer: Superman Address: Metropolis
(4)給word模板克隆表格行
word表格模板如下:
| ${userId} | ${userName} |
| |----------------+
| | ${userAddress} |
實現如下:
$values = [ ['userId' => 1, 'userName' => 'Batman', 'userAddress' => 'Gotham City'], ['userId' => 2, 'userName' => 'Superman', 'userAddress' => 'Metropolis'], ]; $templateProcessor->cloneRowAndSetValues('userId', $values);生成的結果如下:
| 1 | Batman |
| |------------+
| | Gotham City|
| 2 | Superman |
| |-------------+
| | Metropolis |
(5)生成word文檔並保存,使用saveAs方法實現
$templateProcessor->saveAs('test.docx');根據如上就可以實現word模板生成word文檔
