PHPword模板的使用

最近手上的项目需要生成word文档并保存下来,网上搜索了一下找到了PHPword,记录一下,免得以后再用到又去百度一大堆。
项目使用的是thinkPHP5.1框架。
composer安装phpword扩展,cmd切换路径到项目根目录下输入

composer require phpoffice/phpword

安装完成后控制器中引入phpword

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

然后去创建一个word文档用作模板,尽量用office2007(.docx后缀)吧(PS:网上看到phpword对doc的支持不太友好,容易替换失败)。
把word文档的格式都设置好,然后在需要替换内容的地方添加替换标签,模板标签格式为${标签名}如图:PHPword模板的使用_第1张图片
准备工作就绪,开始写代码

public function create_word(){
    $phpWord = new PhpWord;
    //打开模板
    $template = $phpWord->loadTemplate('public/static/doc/template1.docx');
    //模板替换
    $template->setValue('name', '小明');
    $template->setValue('sex', '男');
    $template->setValue('phone_number', '18888888888');
    $template->setValue('email', '[email protected]');
    $template->setValue('school', 'XXX大学');
    $template->setValue('edu', '本科');
    //输出换行到word文档用
    $template->setValue('expertise', '1.PHP2.mysql3.linux');
    $template->setValue('job', 'PHP工程师、全栈工程师、架构师');
    //文件命名
    $fileName = md5(rand(1000, 9999)).'.docx';
    //文件保存路径
    $filePath = 'public/static/create/'.$fileName;
    //保存文件
    $template->saveAs($filePath);
}

调用这个方法

保存为word文档

查看效果
PHPword模板的使用_第2张图片
至此,简单的模板替换就完成了,再加个下载

public function create_word(){
    $phpWord = new PhpWord;
    //打开模板
    $template = $phpWord->loadTemplate('public/static/doc/template1.docx');
    //模板替换
    $template->setValue('name', '小明');
    $template->setValue('sex', '男');
    $template->setValue('phone_number', '18888888888');
    $template->setValue('email', '[email protected]');
    $template->setValue('school', 'XXX大学');
    $template->setValue('edu', '本科');
    //输出换行到word文档用
    $template->setValue('expertise', '1.PHP2.mysql3.linux');
    $template->setValue('job', 'PHP工程师、全栈工程师、架构师');
    //文件命名
    $fileName = md5(rand(1000, 9999)).'.docx';
    //文件保存路径
    $filePath = 'public/static/create/'.$fileName;
    //保存文件
    $template->saveAs($filePath);
    ob_clean();
    if(!is_file($filePath) || !is_readable($filePath)) exit('未找到文件');
    $fileHandle = fopen($filePath,"rb");
    if($fileHandle === false) exit("文件读取失败");
    header("Content-Transfer-Encoding: binary");
    header("Accept-Ranges: bytes");
    header("Content-Length: ".filesize($filePath));
    header('Content-Disposition:attachment;fileName="'.urlencode($fileName).'"');
    while(!feof($fileHandle)) {
        echo fread($fileHandle, 10240);
    }
    fclose($fileHandle);
}

有人也整理了phpword的文档:phpword中文手册整理
phpword官方实例:https://github.com/PHPOffice/PHPWord/tree/develop/samples
phpword官网:https://phpword.readthedocs.io/en/latest/

你可能感兴趣的:(php,thinkphp5.1)