当前位置: 首页 > 后端技术 > PHP

PHPword模板的使用

时间:2023-03-29 16:58:50 PHP

最近手头的项目需要生成一个word文档并保存。我搜索了Internet并找到了PHPword。记录一下,免得以后再用去百度一大堆。项目使用thinkPHP5.1框架。Composer安装phpword扩展,cmd切换路径到项目根目录,输入composerrequirephpoffice/phpword安装完成后,将phpword引入controllerusePhpOffice\PhpWord\IOFactory;使用PhpOffice\PhpWord\PhpWord;然后创建一个word文档作为模板,尝试使用office2007(.docx后缀)(PS:在网上看到phpword对doc的支持不是很友好,容易替换失败)。设置word文档的格式,然后在需要替换内容的地方添加替换标签。模板标签格式为${标签名}如图:准备工作准备就绪,开始写代码publicfunctioncreate_word(){$phpWord=newPhpWord;//打开模板$template=$phpWord->loadTemplate('public/static/doc/template1.docx');//模板替换$template->setValue('name','Xiaoming');$template->setValue('性别','男性');$template->setValue('phone_number','18888888888');$template->setValue('邮箱','18888888888@163.com');$template->setValue('学校','XXX大学');$template->setValue('edu','本科生');//使用$template->setValue('expertise','1.PHP2.mysql3.linux')向word文档输出换行符$template->setValue('job','PHP工程师,全栈工程师,架构师');//文件名$fileName=md5(rand(1000,9999)).'.docx';//文件保存路径$filePath='public/static/create/'.$fileName;//保存文件$template->saveAs($filePath);}调用这个方法保存为word文档查看效果至此简单模板替换完成,然后下载另一个publicfunctioncreate_word(){$phpWord=新的PhpWord;//打开模板$template=$phpWord->loadTemplate('public/static/doc/template1.docx');//模板替换$template->setValue('name','Xiaoming');$template->setValue('性别','男性');$template->setValue('phone_number','18888888888');$template->setValue('邮箱','18888888888@163.com');$template->setValue('学校','XXX大学');$template->setValue('edu','undergraduate');//使用$template->setValue('expertise','1.PHP2.mysql3.linux')将换行符输出到word文档中$template->setValue('job','PHP工程师,全栈工程师,架构师');//文件名$fileName=md5(rand(1000,9999)).'.docx';//文件保存路径$filePath='public/static/create/'.$fileName;//保存文件$template->saveAs($filePath);ob_clean();if(!is_file($filePath)||!is_readable($filePath))exit('找不到文件');$fileHandle=fopen($filePath,"rb");if($fileHandle===false)exit("读取文件失败");标头(“内容传输编码:二进制”);标头(“接受范围:字节”);header("Content-Length:".filesize($filePath));header('Content-Disposition:attachment;fileName="'.urlencode($fileName).'"');while(!feof($fileHandle)){echofread($fileHandle,10240);}fclose($fileHandle);}也有人整理了phpword文档:phpword中文手册整理phpword官方例子:https://github.com/PHPOffice/PHPWord/tree/develop/samplesphpword官网:https://phpword.readthedocs.io/en/latest/

最新推荐
猜你喜欢