按照《Phpword生成word文檔》 http://www.apdwn.com/doc/1103.html 操作成功并實現(xiàn)下載的過程記錄,代碼如下:
<?php namespace Phpcmf\Controllers;
class Doc extends \Phpcmf\Common{
// doc模板文件導(dǎo)出
public function index() {
// 使用系統(tǒng)目錄(http://www.apdwn.com/doc/373.html)把模板文件放在/template/下面
$tpl = TPLPATH.'test.docx';
$PHPWord = new \PhpOffice\PhpWord\PhpWord();
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($tpl);
// 設(shè)置變量,使用時替換比較方便
$name = '張三';
$zhiwei = '公務(wù)員';
$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");
// 取模運算獲取時間戳后四位,防止文件名重復(fù)
$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;
}
}