PHPword操作

php操作word

安装

git 地址 PhpWord

生成和修改word 记得模板文件为 docx格式

模板文件 word文件中 替换的字段标签这样写 ${xxx}

use PhpOffice\PhpWord\TemplateProcessor;

$templateProcessor = new TemplateProcessor('word文件地址');  
// 批量构造合同数据      
$data = [
    'title'               => $model->title,
    'pact_no'             => $model->pact_no,
    'member_id'           => $model->member_id,
    'jiafang'             => $model->jiafang,
    'yifang'              => $model->yifang,
];

$templateProcessor = new TemplateProcessor($tpl['file_path']);  

$templateProcessor->setValues($data);  
// 替换图片
$templateProcessor->setImageValue('yingye_cover', ['path' => $model->yingye_cover, 'width' => 364, 'height' => 500, 'ratio' => true]);


// 保存文件
// 保存地址

$path = __DIR__."/../../../web/attachment/pacts/";
$name = 'pact-'.$id.'-'.time().'.docx';
$file = $path.$name;

$file_ture = $_SERVER['HTTP_HOST']."/attachment/pacts/".$name;

$templateProcessor->saveAs($file);

if(file_exists($file))
{
    // 删除历史合同
    $old = substr($old_file,strripos($old_file,"/")+1);
    $r = @unlink($path.$old);

    $model->pact_path = $file_ture;
    $model->save();
    return ['res'=>true, 'msg'=>'生成合同成功!','data'=>$file_ture];
}
else
{
    return ['res'=>false, 'msg'=>'生成合同失败!'];
}



导航