php 修改word内容,使用PHPWord对Word文件做模板替换

原标题:使用PHPWord对Word文件做模板替换

文章排版有点乱,建议点击左下角的“阅读原文”查看。

因工作需要,使用了版本比较旧的 项目

官方已不见维护更新,上次版本更新是在 Fri Jul 8, 2011 at 8:00 AM

如果PHP版本>=5.3.3,强烈推荐使用 这个开源项目

本篇针对的为旧版本的

基本安装

问题总结 Autoloader 自动加载部分情况下失败

在使用 Yii 1 配置自动加载时无法正常加载类库,需对其 PHPWord/Autoloader.php 做部分调整,这儿借鉴了 PHPExcel 的 Autoloader :

/** * PHPWord_Autoloader */classPHPWord_Autoloader{ /** * Register the Autoloader with SPL * */publicstaticfunctionRegister(){ $functions = spl_autoload_functions(); foreach( $functions as$function) spl_autoload_unregister($function); $functions = array_merge( array( array( 'PHPWord_Autoloader', 'Load')),$functions); foreach( $functions as$function) $x = spl_autoload_register($function); return$x; } // function Register()/** * Autoload a class identified by name * * @paramstring $pClassName Name of the object to load */publicstaticfunctionLoad($pClassName){

if((class_exists($pClassName, FALSE)) || (strpos($pClassName, 'PHPWord') !== 0)) { // Either already loaded, or not a PHPWord class requestreturnFALSE; } $pClassFilePath = PHPWORD_BASE_PATH . str_replace( '_',DIRECTORY_SEPARATOR,$pClassName) . '.php'; if((file_exists($pClassFilePath) === FALSE) || (is_readable($pClassFilePath) === FALSE)) {

// Can't loadreturnFALSE; } require($pClassFilePath); } // function Load()} 模板替换时无法识别模板标签 表现

使用/复制官方样例的模板文件替换正常

自己手动敲出模板标签替换异常原因

PHPWord的替换规则是将 Word 文件解析成 XML 进行替换处理,当 Word 解析成 XML 时字符分离了,导致匹配不上模板标签;

具体分析可参考一下资料:

解决办法

参考

改进 Template 类:

可参考 对 Template 类进行改造。

因为下面仍需要修改 Template 类,这儿暂时就不贴代码了,下面一并贴出改造后的代码。

中文乱码

参考

编辑 PHPWord/Template.php ,找到代码 $replace = utf8_encode($replace); ,删除或者注释掉这行代码,添加 $replace = iconv( 'gbk','utf-8', $replace); ,比如代码改为如下:

/** * Set a Template value * * @parammixed $search * @parammixed $replace */publicfunctionsetValue($search, $replace){ if(substr($search, 0, 2) !== '${'&& substr($search, -1) !== '}') { $search = '${'.$search. '}'; } if(!is_array($replace)) { //$replace = utf8_encode($replace);$replace =iconv( 'gbk', 'utf-8', $replace); // 注释掉上面行后添加这行} $this->_documentXML = str_replace($search, $replace, $this->_documentXML);} 空格输出

参考

在想要输出换行的地方用
代替即可.

标记符号输出

参考

仅以输出 □ 和 ☑ 为例,其它符号与之类似。

注: PHP 文件需要使用 UTF-8 编码

在 Word 文件中按照参考文件方式插入 ☑ ;

复制符号到 PHP 文件;

正常的输出替换。

具体代码见如下的 项目代码。Template 类代码

// code

/*** Set a Template value** @parammixed $search* @parammixed $replace*/

public

functionsetValue($search, $replace, $limit=-1){

if(substr($search,

0,

1) !==

'{'&& substr($search,

-1) !==

'}') { $search =

'{'.$search.

'}'; }

if(!is_array($replace)) {

// $replace = utf8_encode($replace);

// $replace = iconv( 'gbk','utf-8', $replace);$replace = str_replace(

"n",

"
",$replace); } preg_match_all(

'/{[^}]+}/',

$this->_documentXML, $matches);

foreach($matches[

0]

as$k => $match) { $no_tag = strip_tags($match);

if($no_tag == $search) { $match =

'{'.$match.

'}';

$this->_documentXML = preg_replace($match, $replace,

$this->_documentXML, $limit);

if($limit ==

1) {

break; } } }}

// code项目代码

// @author Heier xheier@outlook.com

public

functionactionExportPersonTable(){

// 获取数据部分代码

// ...$PHPWord =

newPHPWord();

// Word模板目录$personBasePath = Yii::app()->basePath.

'/person/';

// 删除目录下临时文件-十分钟以前

$this->delfile( $personBasePath,

10);

// 模板文件名$tempName = $personBasePath .

'/moban.docx'; $word = $PHPWord->loadTemplate( $tempName );

// 项目使用的是GBK编码,需要做转换$username = iconv(

'gbk',

'utf-8', getUserNameById($personData[

0][

'user_id']) ); $personal_type = $personData[

0][

'personal_type'];

// 模板替换开始

// 可以输出打勾的方框$deptA=$deptBP=$deptB=$deptC=$deptD =

'□';

if( $DirectorLevel ==

'A') { $deptA =

'☑'; }

elseif( $DirectorLevel ==

'B+') { $deptBP =

'☑'; }

elseif( $DirectorLevel ==

'B') { $deptB =

'☑'; }

elseif( $DirectorLevel ==

'C') { $deptC =

'☑'; }

elseif( $DirectorLevel ==

'D') { $deptD =

'☑'; } $word->setValue(

'deptA', $deptA); $word->setValue(

'deptBP', $deptBP); $word->setValue(

'deptB', $deptB); $word->setValue(

'deptC', $deptC); $word->setValue(

'deptD', $deptD);

// 设置其它替换

// ...

// 生成临时文件以供下载$tmpFileName = md5( time().

'Heier'); $word->save($personBasePath .

'/'. $tmpFileName .

'.docx'); $file = $personBasePath .

'/'. $tmpFileName .

'.docx';

// 下载Word文件ob_start();

//打开缓冲区$fp = fopen($file,

"r"); $file_size = filesize($file); $downFileName =

'XXX.docx'; header(

"Cache-Control: public"); header(

"Content-type: application/octet-stream"); header(

"Accept-Ranges: bytes"); header(

"Content-Disposition: attachment; filename={$downFileName}"); header(

"Pragma:no-cache"); header(

"Expires:0"); $buffer =

1024; $file_count =

0;

//向浏览输出回数据

while(!feof($fp) && $file_count < $file_size){ $file_con = fread($fp,$buffer); $file_count += $buffer;

echo$file_con; } ob_end_flush();

//输出全部内容到浏览器} 参考文档汇总

;

;

;

;

;

;

关注微信公众号:PHP技术大全

PHPer升级为大神并不难!返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值