php word组件使用方法,phpword使用笔记

phpword使用的人不多,国内相关文档也比较少,所以坑比较多。我在这里躺坑躺了一整天,记录一下以备后需。

1、使用phpword需要很多组件的支持,所以用composer来安装管理他

a、下载phpword,放到组件目录;

b、下载并且运行 Composer-Setup.exe,它将安装最新版本的 Composer ,并设置好系统的环境变量,因此你可以在任何目录下直接使用 composer 命令。(到环境变量检查下,是否配置环境变量,这样在任何目录都可以使用composer);

c、composer进入到phpword目录下composer install即可。

2、使用需要引入的文件

只需要引入phpword安装包目录下的bootstrap.php即可。

require_once 'inc/PHPWord-master/bootstrap.php';

3、使用中文报错。

比如:

InvalidArgumentException' with message 'Invalid style value: chineseCounting

Invalid style value: japaneseCounting

解决办法:

找到PhpWord\Style\NumberingLevel.php这个文件中的public function setFormat($value)方法

里面$enum数组中添加“chineseCounting”和“japaneseCounting“;

eg:

public function setFormat($value)

{

$enum = array('bullet', 'decimal', 'upperRoman', 'lowerRoman', 'upperLetter', 'lowerLetter', 'chineseCounting','japaneseCounting');

$this->format = $this->setEnumVal($value, $enum, $this->format);

return $this;

}

4、模板替换

很多时候,我们使用一个word模板,然后把里面要修改的部分设置为预定义标签,然后使用模板替换,就可以快速简便的生成想要的文档。

参考官方文档:http://phpword.readthedocs.io/en/latest/templates-processing.html

5、phpword内部循环输出内容

请参考官方文档,这里给个例子

require_once 'inc/PHPWord-master/bootstrap.php';//加载word组件支持

$wordmuban = $_SERVER['DOCUMENT_ROOT'].'/inc/word.docx';//模版文件目录

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($wordmuban);//加载文件模版创建新word文件

$templateProcessor->cloneRow('num', $sizenum);//复制循环的行,请参考官方文档

//复制循环的行后,之前模板中的标签会被自动编号“标签+#行数”

for($i=1;$i<=$sizenum;$i++){

$templateProcessor->setValue('num#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['num']));

$templateProcessor->setValue('type1#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['type1']));

$templateProcessor->setValue('type2#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['type2']));

$templateProcessor->setValue('level#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['level']));

$templateProcessor->setValue('areasize#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['areasize']));

$templateProcessor->setValue('price#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['price']));

$templateProcessor->setValue('amountprice#'.$i, iconv("gbk","utf-8",$sizedata[$i-1]['amountprice']));

}

//创建文件目录

if (!file_exists($dir)){

mkdir ($dir,0755,true);

}

$savefile = $templateProcessor->saveAs($filename);//保存文件

未完待续

遇到的问题与解决办法:

1、phpword错误提示'Could not close zip file XXX‘

问题原因:phpword的模板文件必须是docx,如果是doc的文档,必须把模板文件另存为docx,即可解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值