PHPWord简介与安装
本教程详细解析利用PHPWord库创建Word文件的完整流程,提供实用参考。
当需要将网页数据导出为Word格式以便他人查阅或编辑时,PHPWord这一纯PHP库能简化文档内容的处理与生成过程。
获取源码
环境准备
推荐使用Composer工具进行PHPWord的安装部署。
composer require phpoffice/phpword
基本用法
依赖引入
完成安装后,新建PHP文件并引入autoload.php以加载依赖。
require 'vendor/autoload.php';
初始化对象
创建PhpWord实例并添加一个空白页面区域。
$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);
超链接
支持为文档内的文字添加可点击跳转的URL链接。
$section->addLink('https://www.helloweba.net', '欢迎访问Helloweba', array('color' => '0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));
$section->addTextBreak();
图像嵌入
可在文档中插入图片,例如指定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!');
页脚配置
为文档添加页脚,通常用于显示页码并保持居中格式。
$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');
直接下载
若希望用户直接下载文件而不保留在服务器,可使用如下方式:
$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的功能细节,请参阅官方文档:http://phpword.readthedocs.org/.
期望本文内容能对各位PHP开发者的程序设计工作带来帮助。