phpword 模板替换并导出教程
word 模板文件定义
楼主在 public\uploads\application\template.docx 该路径下面创建了 word 的模板文件template.docx
该模板文件含有若干个形如 “ $ {baby_station} ” 的变量,这些变量就是用来在下面export方法中进行替换的。
注意:“$ {baby_station} ”这类变量应该在 sublime 类的编辑器中写好再复制粘贴进 word 文档中,不然word 可能无法编辑或者导致模板无法识别变量
PHPword 类库
类库链接:https://github.com/PHPOffice/PHPWord
我使用的是thinkphp5 框架,类库放在extend下面
控制器引入类库
use PhpOffice\Common\Font;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor; // 模板替换只需要引入这个类
控制器export方法操作类库
/**
** phpword 模板替换并下载
**/
public function export()
{
//指定模板文件
$templateProcessor = new TemplateProcessor("uploads/application/template.docx");
//通过setValue 方法给模板赋值
$templateProcessor->setValue('baby_station', $baby_station);
$dir = iconv("UTF-8", "GBK", "uploads/application/".date(Ymd).'/');//保存路径
if (!file_exists($dir)){
mkdir ($dir,0777,true); // 如果保存目录不存在就创建新目录
}
$filename = $dir.date(YmdHis).'.docx';
$templateProcessor->saveAs($filename); //另存为新word文档,根据模板和变量生成了新的文档
// 下载文档
$file_dir = $filename; //下载文件存放目录
//检查文件是否存在
if (! file_exists ( $file_dir )) {
header('HTTP/1.1 404 NOT FOUND');
} else {
$file = fopen ( $file_dir, "rb" );//以只读和二进制模式打开文件
Header ( "Content-type: application/octet-stream" ); //告诉浏览器这是一个文件流格式的文件
Header ( "Accept-Ranges: bytes" ); //请求范围的度量单位
Header ( "Accept-Length: " . filesize ( $file_dir ) ); //Content-Length是指定包含于请求或响应中数据的字节长度
//用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。
Header ( "Content-Disposition: attachment; filename=下载名称.docx" );
echo fread ( $file, filesize ( $file_dir ) ); //读取文件内容并直接输出到浏览器
fclose ( $file );
exit ();
}
}
模板替换只是 phpword 操作 word 的一种方式,另外一种是直接手写生成word文档的方式,有兴趣的欢迎私聊一起学习一下,或者我再抽空写一下另一种方式。
转载请注明出处,谢谢。