A-A+

phpword使用笔记

2017年12月08日 php 暂无评论 阅读 6,566 views 次

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,即可解决。

标签:

给我留言