php导出信息到word文档

网址:https://github.com/PHPOffice/PHPWord

 

对于将信息导出到word文档的方式,用一个word文档作为模板,替换其中的变量是最简单不过的了。

附件中提供了这样的实例,亲测可用,我还百度搜索,扩展了图片替换的方法(见:http://stackoverflow.com/questions/24018003/how-to-add-set-images-on-phpoffice-phpword-template)。

要说的是是,这个只支持docx。doc不行。因为处理方式使用了zip解压缩的方法。

代码贴出来:

 

<?php
require_once 'bootstrap.php';


$PHPWord = new \PhpOffice\PhpWord\PhpWord();
$document = $PHPWord->loadTemplate('Tpl.docx');
$document->setValue('title', 'phpword替换模板');
$document->setValue('date', '2017-03-20');
$document->setImageValue('image1.jpeg', './2.png');
$document->saveAs('Out.docx');

 

这里面注意一下,插入的图片无论文件名为什么,都会被word文档修改为image1.jpeg, image2.png等,具体是什么,可以将word文档拷贝一份,修改为xxx.zip,然后解压缩,这时候解压出来是一个目录,打开目录,里面有word/media目录,打开后就能知道具体图片的名字了,这时候再去写代码,是最靠谱的。

 

猜你喜欢

转载自canlynet.iteye.com/blog/2364151