laravel通过模板html生成word文档
因为公司项目需要,内部的管理系统有一个php实时查询数据库,根据内容来生成word文档
排版没有什么需求,实现原理是查询数据库,然后用laravel自带的模板引擎,生成一个html网页,然后修改网页的response的header头,让浏览器下载为word格式。
代码如下
public function highAnswerDowload(Request $request)
{
$id = (int)$request->input('id');
$data = LibraryTopicModel::with(['library:id,name', 'answer' => function ($query) {
return $query->where('status', 1);
}, 'answer.member:id,name,phone'])->find($id);
if (!isset($data))
return self::errorMsg('没有找到该题目');
$html = view('word', ['data' => $data]);
$wordname = $data['library']['name'] . date('Y-m-d') . "待审核高分答案.docx";
ob_start();
echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">';
@header('Content-type:application/word');
header('Content-Disposition: attachment; filename=' . $wordname . '');
@readfile($wordname);
ob_flush();//每次执行前刷新缓存
flush();
return $html;
}
模板文件
<html lang="zh-cn"> <head> <style type="text/css"> p { text-indent: 2em; font-size: 12pt; } </style> </head> <body> <center><h1>{{$data['library']['name']}}</h1></center> <b> {{$data['title']}} -- 题目id:{{$data['id']}} </b> <br> <br> @foreach($data['answer'] as $v) <div> <div style="font-weight: bold"> <div>昵称:{{$v['member']['name']}} id:{{$v['member_id']}} 手机:{{$v['member']['phone']}} </div> <div>答案id:{{$v['id']}} 日期:{{date('Y-m-d H:i',$v['create_time'])}}</div> </div> <?php $content = explode("\n", $v['content']); ?> @foreach($content as $j) <p> {{$j}} </p> @endforeach —————————————————————————————————— <br> </div> @endforeach </body> </html>
