美文网首页
php使用phpWord按照模板导出word文件

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

作者: 怀老师 | 来源:发表于2022-11-09 09:36 被阅读0次
    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来实现的。

    相关文章

      网友评论

          本文标题:php使用phpWord按照模板导出word文件

          本文链接:https://www.haomeiwen.com/subject/tqawtdtx.html