话不多说,直接开干

1、composer安装phpword包

1
composer require phpoffice/phpword

2、准备一个word模板

简单案列:

上图为原模板,我们替换姓名和邮箱,就拿两个变量替换原模板文字,操作如下:

3、渲染变量操作

1
2
3
4
5
include_once "vendor/autoload.php";
$word=new \PhpOffice\PhpWord\TemplateProcessor('word.docx');//打开模板,模板地址需要绝对路径
$word->setValue('name','heyiki');//替换变量name
$word->setValue('email','[email protected]');//替换变量email
$word->saveAs('test.docx');//另存为,地址需要绝对路径,注意命名别用中文

打开test.docx文档将看见,变量已经替换,完成如图1

简单封装

引入:

1
2
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\IOFactory;

封装方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* word文档变量替换
* @param string $tmpurl 模板word路径
* @param array $search 搜索文档中的变量名 一维数组:['param1','param1']
* @param array $replace 需替换变量名的值 一维数组:['value1','value1']
* $param string $alias 别名
* $param string $pic_replcae 图片替换(如个人照,公章等)
* @param int $type 类型 0-模板替换生成新文档 1-获取文档追加更新
*/
public status function replaceWord($tmpurl = '', $search = [], $replace = [] , $type = 0, $alias = '',$pic_replcae = [])
{
try {
if(!$tmpurl) return ['code'=>500,'msg'=>'模板文件为空'];
//模板work文档,替换成绝对路径
$tmpUrl = str_replace(request()->domain().'/',env("root_path"),$tmpurl);
$tp = new TemplateProcessor($tmpUrl);
//替换变量
$tp->setValue($search,$replace);

if($pic_replcae){//将图片替换成绝对路径
$image = str_replace(request()->domain().'/',env("root_path"),$pic_replcae['image']);
$tp->setImageValue($pic_replcae['search'],['path'=>$image,"width" => 150, "height" => 150]);
}

if($type == 0){
//设置保存文件名
$firstName = env("root_path").'public/upload/word/';
$alias = $alias ? $alias.'_'.time().".docx" : time().".docx";
$firstName = $firstName.$alias;
//保存文档
$tp->saveAs($firstName);
//生成文件名
$name = pathinfo($firstName,PATHINFO_FILENAME);
//新文件路径
$newUrl = request()->domain()."/uploads/word/".$name.".docx";
return ['code'=>200','data'=>['url'=>$newUrl]];

} elseif($type == 1){
//获取文件名
$name = pathinfo($tmpurl,PATHINFO_FILENAME);
//设置保存文件名
$firstName = env("root_path").'public/upload/word/'.$name.".docx";
//更新保存文档
$tp->saveAs($firstName);
return ['code'=>200','data'=>['url'=>$newUrl]];
}

} catch (\Exception $e) {
return ['code'=>500,'msg'=>$e->getMessage()];
}
}

方法调用实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

//获取模板文档地址
$tp_word_url = "项目地址/test.docx";

//变量名(模板设置的变量)
$search = ['name','email'];

//替换值
$replace = ['heyiki','[email protected]'];

$callback = PhpWordLogic::replaceWord($tp_word_url, $search, $replace, 0, 'test');

图片替换不能与文字替换混在一起,如模板文档的变量值为:img

$callback = PhpWordLogic::replaceWord($tp_word_url, $search, $replace, 0, 'test', ['image'=>'项目地址/123.png','search'=>'img']);