2、将PhpWord放在extend下面
3、将模板文件 temp.docx 放在public 目录下面,模板中使用${变量名}作为占位符,到时候用代码替换即可
4、代码如下
<?php
namespace app\admin\controller;
use think\Db;
class Index extends Base
{
public function daochu3()
{
import('PhpOffice\PhpWord\TemplateProcessor');
//1.创建模板对象
$document = new \PhpOffice\PhpWord\TemplateProcessor('temp.docx');
//2.插入数据
$document->setValue('group', '测试组');
$document->setValue('unit', '几度');
$document->setValue('leader_name', '小度');
$document->setValue('leader_phone', '18888888888');
$document->setValue('leader_card', '34888888888888888888');
$document->setValue('coach1_name', '小度2');
$document->setValue('coach1_phone', '18888888888');
$document->setValue('coach1_card', '34888888888888888888');
$document->setValue('coach2_name', '小度3');
$document->setValue('coach2_phone', '18888888888');
$document->setValue('coach2_card', '34888888888888888888');
$document->setValue('father1', '小度爸爸');
$document->setValue('father1_card', '346666666666666666');
$document->setValue('mother1', '小度妈妈');
$document->setValue('mother1_card', '346666666666666666');
$document->setValue('child1', '小度妈妈');
$document->setValue('child1_name', '346666666666666666');
$document->setValue('father2', '小度爸爸2');
$document->setValue('father2_card', '346666666666666666');
$document->setValue('mother2', '小度妈妈2');
$document->setValue('mother2_card', '346666666666666666');
$document->setValue('child2', '小度妈妈2');
$document->setValue('child2_name', '346666666666666666');
$document->setValue('father3', '小度爸爸3');
$document->setValue('father3_card', '346666666666666666');
$document->setValue('mother3', '小度妈妈3');
$document->setValue('mother3_card', '346666666666666666');
$document->setValue('child3', '小度妈妈3');
$document->setValue('child3_name', '346666666666666666');
$document->setValue('remark', '小度的备注');
//3.保存文件
$document->saveAs('./temp_copy.docx');
//4.从浏览器下载
ob_clean();
ob_start();
$fp = fopen('temp_copy.docx',"r");
$file_size = filesize('temp_copy.docx');
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Accept-Length:".$file_size);
header("Content-Disposition:attchment; filename=".'测试文件.docx');
$buffer = 1024;
$file_count = 0;
while (!feof($fp) && $file_count < $file_size){
$file_con = fread($fp,$buffer);
$file_count += $buffer;
echo $file_con;
}
fclose($fp);
ob_end_flush();
}
}5、附上百度网盘链接链接:https://pan.baidu.com/s/1258aidSYQIr589oM3WiUaw提取码:07uj
最佳答案