按照《Phpword生成word文档》 https://www.xunruicms.com/doc/1103.html 操作成功并实现下载的过程记录,代码如下:
<?php namespace Phpcmf\Controllers;
class Doc extends \Phpcmf\Common{
// doc模板文件导出
public function index() {
// 使用系统目录(https://www.xunruicms.com/doc/373.html)把模板文件放在/template/下面
$tpl = TPLPATH.'test.docx';
$PHPWord = new \PhpOffice\PhpWord\PhpWord();
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($tpl);
// 设置变量,使用时替换比较方便
$name = '张三';
$zhiwei = '公务员';
$bianhao = '360281199909090009';
$uptime = date("Y-m-d H:i:s");
// 开始对模板赋值
$templateProcessor->setValue('name', $name);
$templateProcessor->setValue('zhiwei', $zhiwei);
$templateProcessor->setValue('bianhao', $bianhao);
$templateProcessor->setValue('uptime', $uptime);
$date = date("Y-m-d");
// 取模运算获取时间戳后四位,防止文件名重复
$timeDigits = time() % 10000;
// 下面的test以后可以改成变量
$filename = 'test-'.$date.'-'.$timeDigits;
// 保存新的文件到uploadfile\phptodocx\下面,注意phptodocx\后面不加\就不行了。
$templateProcessor->saveAs(WEBPATH.'uploadfile\phptodocx\\'.$filename.'.docx');
// 生成下载链接
echo "<a href='/uploadfile/phptodocx/".$filename.".docx' target='_blank'>".$filename."</a>";
exit;
}
}