当前位置: 移动技术网 > IT编程>开发语言>PHP > 使用PHPWord生成word文档的方法详解

使用PHPWord生成word文档的方法详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了使用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文档:.

更多关于php相关内容感兴趣的读者可查看本站专题:《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php数组(array)操作技巧大全》、《php数据结构与算法教程》、《php程序设计算法总结》、《php数学运算技巧总结》、《php正则表达式用法总结》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总

希望本文所述对大家php程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网