使用phpword生成文档有两种方式
- 直接使用代码编写word文档,用代码生成word,但是设置样式,格式,图片非常麻烦,不建议使用。如果客户或产品提供一份word的样式,我们也难以完全复原,调样式很头疼的。
- 读取原有word模板,替换相关变量。个人感觉这种方式能满足绝大部分需求,实现起来也比较简单,所有的样式,格式直接在word模板里设置好,替换变量就可以了,还可以很方便的切换模板。本文主要介绍这种方式,毕竟我们是为了快速实现客户的需求,让客户提供一份word模板,我们稍微一改就可以了。
开始干活
1,通过composer安装phpword包
composer require phpoffice/phpword
2,准备一个word模板(让客户或产品提供吧,docx格式的)
$tpl = \'template/word/display_agreement.docx\'; $doc = new TemplateProcessor($tpl);//打开模板 // 简单替换 $doc->setValue(\'dealer_name\', $oneCust->dealer->dealer_name, 2);//替换变量 第二个参数替换次数 $doc->setValue(\'cust_name\', $oneCust->customer->cust_name);//替换变量cust_name $doc->setValue(\'start_time\', $arrOneCust[\'start_time_text\']); $doc->setValue(\'end_time\', $arrOneCust[\'end_time_text\']); $doc->setValue(\'show_day\', $arrOneCust[\'show_day\']); $doc->setValue(\'signing_date\', date(\'Y年m月d日\', $arrOneCust[\'create_at\'])); // 陈列要求 // 循环替换 $arr = [ [\'goods_name\'=>\'苹果手机8\',\'specs\'=>\'128G\',\'number\'=>\'2台\'], [\'goods_name\'=>\'苹果手机11\',\'specs\'=>\'128G\',\'number\'=>\'2台\'], [\'goods_name\'=>\'苹果手机12\',\'specs\'=>\'128G\',\'number\'=>\'2台\'], ] if (!empty($arr)) { $j = 1; $rows = count($arr); $doc->cloneRow(\'customergoods_name\', $rows);//复制行 foreach ($arr as $oneGoods) { $dTmp = $oneGoods->toArray(); $doc->setValue(\"customergoods_name#\" . $j, \"产品名称:{$oneGoods[\'goods_name\']}\");//替换变量 $doc->setValue(\"customergoods_spce#\" . $j, \"产品规格:{$oneGoods[\'specs\']}\");//替换变量 $doc->setValue(\"customergoods_num#\" . $j, \"数量:{$oneGoods[\'number\']}\");//替换变量 $j++; } }
有时我们需要有“陈列奖励”数据时就显示没有时就不显示,此里需要用到块标签了与html类似
// 陈列奖励 // 循环替换 $arr = [ [\'goods_name\'=>\'苹果手机8\',\'time\'=>\'1606011063\',\'number\'=>\'2台\'], [\'goods_name\'=>\'苹果手机11\',\'time\'=>\'1606011063\',\'number\'=>\'2台\'], [\'goods_name\'=>\'苹果手机12\',\'time\'=>\'1606011063\',\'number\'=>\'2台\'], ] $doc->cloneBlock(\'WIN_BLOCK\',0); if (!empty($arr)) { //显示块 $doc->cloneBlock(\'WIN_BLOCK\',1); $j = 1; $rows = count($arr); $doc->cloneRow(\'customergoods_name\', $rows);//复制行 foreach ($onePhase->customerGoodList as $oneGoods) { $doc->setValue(\"phase_date#\" . $j, date(\'Y-m-d\', $onePhase[\'time\']));//替换变量 $doc->setValue(\"phase_type#\" . $j, \'兑付\');//替换变量 $doc->setValue(\"phase_goods#\" . $j, $oneGoods[\'goods_name\']);//替换变量 $doc->setValue(\"phase_num#\" . $j, \"数量:{$oneGoods[\'number\']}\");//替换变量 $j++; } }
替换图片
// 只渲染 $tmp->setImageValue(\'header\',[\'path\'=>\'1.jpeg\']); // 设置图片宽高 $tmp->setImageValue(\'header\', [\'path\' => \'1.jpg\',\'width\'=>500,\'height\'=>500]); // 设置多次替换 $tmp->setImageValue(\'header\', [\'path\' => \'1.jpg\',\'width\'=>500,\'height\'=>500],3);
一些常用的word符号
换行符 <w:br/>
分页符 <w:br w:type="page"/>
制表符 <w:tab/>
html预留字符要替换为实体字符,如&要替换为&,可以使用htmlspecialchars()
使用方式
比如我们数据库存的换行符一般是 \\n\\r 这个在word中是无效的,要替换为 <w:br/> 才行
$content = str_replace(\"\\r\\n\", \'<w:br />\', $content); $doc->setValue(\'content\', $content); //内容
© 版权声明
THE END
暂无评论内容