thinkphp5 使用PHPWord(下载引入/composer与模板/生成方式搭配使用)方法
下载地址:https://github.com/PHPOffice/PHPWord
推荐使用模板方式,使用方便,样式也好调一些,大部分要求也都可以实现;生成方式目前我是在做表格单元格合并的时候用到过,下面会介绍使用方式(模板方式在单元格中插入一个小表格,然后用cloneRow复制小表格也可以实现,但是这样比较别扭,不完美)
一:引入
适用tp5.0,tp5.1:
1:composer方式(推荐)
a:根目录下执行:composer require phpoffice/phpword
b:引入:
use PhpOffice\PhpWord\PhpWord;
2:下载引入方式
a:下载PHPWord:
b:放到项目根目录extend文件夹下,目录结构如下:
c:引入
use PhpOffice\PhpWord\PhpWord;
使用方法
ob_clean(); //防止乱码$file = '../extend/files/pdf.docx';//路径,可更改 $PHPWord = new PhpWord(); $template = $PHPWord->loadTemplate($file);//加载模板 $template->setValue('title', '标题');//替换值 $file = date('Y-m-d-H-i-s') . '.docx';//文件名 $encoded_filename = urlencode($file); // 将文件名进行urlencode转码 $file = str_replace('+', '%20', $encoded_filename); header("Content-Description: File Transfer"); header('Content-Disposition: attachment; filename="' . $file . '"'); header('Content-Type:application/vnd.openxmlformats-officedocument.wordprocessingml.document'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Expires: 0'); $template->saveAs('php://output'); //替换值(模板内为${title},如模板图) $template->setValue('title', '标题'); //选择框(模板内为check0和check1<字体是【Wingdings 2】>,替换时R是选中,£是未选,如模板图) $template->setValue('check0', 1? 'R' : '£');//与模板内check0对应,变量命名可更改,与模板一致即可 $template->setValue('check1', 0? 'R' : '£');//与模板内check1对应,变量命名可更改,与模板一致即可 //复制行 $template->cloneRow('本行最左边的变量名', '要复制的行数'); //复制行-举例(如模板图) $user = [['no'=>'1', 'name'=>'张三', 'sex'=>'男'], ['no'=>'2', 'name'=>'李四', 'sex'=>'女']]; $rows = count($user); $template->cloneRow('no', $rows);//复制行,no是要复制行的最左边变量,$rows代表复制几行,复制后会是no#1,name#1,sex#1;no#2,name#2,sex#2这样的 for ($i = 0; $i < $rows; $i++) { $template->setValue('no#' . ($i + 1), $user[$i]['no']); $template->setValue('name#' . ($i + 1), $user[$i]['name']); $template->setValue('sex#' . ($i + 1), $user[$i]['sex']); } //复制块,也可用于是否显示 $template->cloneBlock('块标签名','数量');//模板内为${块标签名}和${/块标签名}和html标签一样,成对出现,内容放中间 //复制块-举例(如模板图) $show_name='显示'; $template->cloneBlock('show', 2);//复制两个 $template->setValue('show_name', $show_name);//设置值 $template->cloneBlock('hide', 0);//复制0个,代表隐藏,值也不用设了 //插入图片(模板内为${img}) $template->setImageValue('img', ['path'=>'路径', 'width'=>500, 'height'=>500]);
更多使用方法可看官方说明:https://phpword.readthedocs.io/en/latest/
本文来源:功夫码(gongfuma.com)
声明:本文系功夫码原创稿件,版权属[功夫码 gongfuma.com]所有。
未经授权不得转载,已经协议授权的媒体下载使用时须注明"稿件来源:功夫码",违者将依法追究责任。