一:安装phpword插件composerrequirephpoffice/phpwordphpwordGitHub地址:https://github.com/PHPOffice/PHPWordphpword文档地址:https://phpword.readthedocs.io/en/latest/二:phpword使用phpword很好简单,可以根据github教程实现,这里我讲解两种生成word文档的方法1:使用html模板生成word文档//html模板信息$html='
111
'$phpWord=新的PhpWord();$section=$phpWord->addSection();\\PhpOffice\\PhpWord\\Shared\\Html::addHtml($section,$html,false,false);$objWriter=\\PhpOffice\\PhpWord\\IOFactory::createWriter($phpWord,'Word2007');$filename='test.docx';$objWriter->保存($文件名);如上,可以将html模板信息生成成word文档,如果要下载word文档header('Content-Type:application/vnd.openxmlformats-officedocument.wordprocessingml.document');header('Content-Disposition:attachment;filename="'.$title.'.docx"');header('缓存控制:max-age=0');//html信息$html='111
'$phpWord=newPhpWord();$section=$phpWord->addSection();\\PhpOffice\\PhpWord\\Shared\\Html::addHtml($section,$html,false,false);$objWriter=\\PhpOffice\\PhpWord\\IOFactory::createWriter($phpWord,'Word2007');$objWriter->save('php://output');2:使用word模板生成word文档(1)加载word模板$templateProcessor=newTemplateProcessor('test.docx');(2)给word模板变量赋值如果给定一个模板:模板信息为:${name}user:${username}给上面模板的name和username变量赋值','单词模板');$templateProcessor->setValue('用户名','测试');我们也可以同时给多个变量赋值(3):如果要将图片赋值给变量将图片赋值给变量,可以使用setImageValue方法设置图片$templateProcessor->setImageValue('img','logo.png');我们还可以设置图片的样式$templateProcessor->setImageValue('img',['path'=>'logo.png','width'=>100,'height'=>100,'ratio'=>错误的]);(3)循环模板词模板如下:${block\_name}Customer:${customer\_name}Address:${customer\_address}${/block\_name}循环及赋值方法如下:$更换cements=array(array('customer_name'=>'Batman','customer_address'=>'GothamCity'),array('customer_name'=>'Superman','customer_address'=>'Metropolis'),);$templateProcessor->cloneBlock('block_name',0,true,false,$replacements);此时生成的结果如下:客户:蝙蝠侠地址:哥谭市客户:超人地址:大都会(4)克隆单词模板的表行单词表模板如下:|${userId}|${用户名}|||----------------+|'=>1,'userName'=>'蝙蝠侠','userAddress'=>'哥谭市'],['userId'=>2,'userName'=>'超人','userAddress'=>'大都会'],];$templateProcessor->cloneRowAndSetValues('userId',$values);生成结果如下:|1|蝙蝠侠|||------------+||哥谭市||2|超人|||------------+||大都会|(5)生成word文档并保存,使用saveAs方法实现$templateProcessor->saveAs('test.docx');根据如上,可以实现word模板生成word文档