php使用phpWord按照模板导出word文件

image.png

需求描述:业务方给了个word模板,需要我们查出来数据填充进去,并且导出为word文件。部分地方需要循环多行展示。

准备工作:

composer require phpoffice/phpword
拉取phpWord扩展

代码:

//加载模板word所需的类
use PhpOffice\PhpWord\TemplateProcessor;

//加载模板文件
public function export(){
     $template = new TemplateProcessor(ROOT_PATH . '/demo.docx');
    //查出需要展示的数据
    $data = ['date'=>'2022-11-08','number'=>123];
    $template->setValues($data);
    //查出需要循环的数据
   $each_data = [
          ['goods_no'=>123,'description_en'=>'a'],
          ['goods_no'=>234,'description_en'=>'b']
    ] ;
    $template->cloneRowAndSetValues('goods_no', $each_data);
    //文件命名并保存到本地
    $file_name = "test.docx";
    $saveDir= $path = ROOT_PATH . '/';
    if (!file_exists($saveDir)) {
            mkdir($saveDir, 0777, true);
    }

   $filepath = $saveDir.'/'.$file_name;
   $template->saveAs($filepath);
   //输出到浏览器下载
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($filepath));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);

}


注意事项:

1:模板变量的命名规则是$符号加上一个大括号,然后变量名写在里面。例如${date}。
2:循环是基于首行的key来实现的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容