目的:PHP通过PHPWord类库导出文件为word。
开发语言及类库:ThinkPHP、PHPWord
项目根目录使用composer安装PHPWord,安装完成后会在vendor目录下生成phpoffice文件夹,就是PHPWord类库
composer require phpoffice/phpword
前端代码
<button type="button" class="layui-btn layui-btn-normal word"><i class="fa fa-file-word-o" aria-hidden="true">i> 导出分析报告 Wordbutton>
- // 下载word
- $(".word").click(function () {
- var shijuan_id = GetQueryString('shijuan_id')
- var grade_id = GetQueryString('grade_id')
- $.ajax({
- url:"exportreport2",
- type:'get',
- dataType:'JSON',
- data:{shijuan_id:shijuan_id,grade_id:grade_id},
- success:function (res) {
- console.log(res)
- if (res.code == '200') {
-
- var index = layer.alert('导出成功,请点击下载!', {
- skin: 'layui-layer-lan' //样式类名
- ,closeBtn: 0
- , btn: ['下载'] //按钮
- }, function(){
- // 触发a链接点击事件
- downloadDom.find('span').click();
- setTimeout(function(){ layer.close(index); }, 500);
-
- });
- }else{
- layer.msg('导出失败,请重试~')
- }
- }
- })
- })
PHP代码
- use PhpOffice\PhpWord\IOFactory;
- use PhpOffice\PhpWord\PhpWord;
-
- public function exportreport2()
- {
- $shijuan_id = trim(input('post.shijuan_id'));
- $grade_id = trim(input('post.grade_id'));
-
- try {
- // 班级、试卷信息
- $info = model('Shijuan')->getShijuanGradeInfo($shijuan_id,$grade_id);
-
- // 标题
- $title = $info['filename'].'_考试分析报告';
- // 文件名
- $docxname = $info['grade'].'_'.$info['year'].$info['season'].'_'.$info['filename'].'_考试分析报告'.date('YmdHis',time());
-
- // 分析报告 二维数组
- $list = model('Shijuan')->getStudyReport($shijuan_id,$grade_id);
-
- // 实例化
- $phpWord = new PhpWord();
- header("Content-Type: text/html; charset=UTF-8");
-
- $phpWord->addFontStyle('cStyle', array('size' => 12,'name' => 'msyh'));//内容样式
- $phpWord->addFontStyle('bStyle', array('size' => 12, 'bold' => true, 'name' => 'msyh'));//加粗样式
- $phpWord->addFontStyle('titlestyle', array('bold' => true,'size' => 16,'name' => 'msyh'));//标题的样式
-
- // 创建新页面
- $section = $phpWord->addSection();
-
- $section->addText($title,'titlestyle', ['alignment' => 'center']);
- $section->addTextBreak(1);
- $section->addText('班级:'.$info['grade'].'_'.$info['year'].$info['season'], 'cStyle', ['alignment' => 'right']);
- $section->addText('总人数:'.$info['student'].'; 已交卷:'.$info['cmit'], 'cStyle', ['alignment' => 'right']);
- $section->addText('导出时间: '.date('Y-m-d H:i:s',time()), 'cStyle', ['alignment' => 'right']);
-
- // 表格样式
- $styleTable = array( 'borderSize'=>6, 'alignment' => 'center','cellMargin'=>80);
- // 第一行样式
- $styleFirstRow = array('bgColor'=>'f2f2f2' );
- $phpWord ->addTableStyle('myOwnTableStyle',$styleTable,$styleFirstRow);
-
- foreach($list as $k=>$v) {
-
- $section->addText('【'.$v['type'].'】 第'.($k+1).'题: '.$v['title'],'cStyle');
- $section->addText('【正确答案】: '.$v['answer'],['alignment' => 'center'],'cStyle');
- $section->addText('【正确率】'.$v['percent'].'%; 【作答人数】: '.$v['cmit_num'].'人次',['color' => '009688'],'cStyle');
-
- // 添加表格
- $table = $section->addTable('myOwnTableStyle');
-
- //添加一行(addRow执行后才能使用addCell给本行添加列,括号内数字代表高度)
- $table->addRow(100);
- //表头添加(数字代表宽度,valign代表对齐方式)
- $table->addCell(3000)->addText('选项', 'bStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText('选择次数/人次','bStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText('比例', 'bStyle', ['alignment' => 'center']);
- // 选择题
-
- $table->addRow(100);
- $table->addCell(3000)->addText('A:'.$v['option_A'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_A'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_A'].'%', 'cStyle', ['alignment' => 'center']);
-
- $table->addRow(100);
- $table->addCell(3000)->addText('B:'.$v['option_B'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_B'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_B'].'%', 'cStyle', ['alignment' => 'center']);
-
- $table->addRow(100);
- $table->addCell(3000)->addText('C:'.$v['option_C'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_C'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_C'].'%', 'cStyle', ['alignment' => 'center']);
-
- $table->addRow(100);
- $table->addCell(3000)->addText('D:'.$v['option_D'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_D'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_D'].'%', 'cStyle', ['alignment' => 'center']);
-
- $table->addRow(100);
- $table->addCell(3000)->addText('E:'.$v['option_E'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_E'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_E'].'%', 'cStyle', ['alignment' => 'center']);
-
- $table->addRow(100);
- $table->addCell(3000)->addText('F:'.$v['option_F'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_F'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_F'].'%', 'cStyle', ['alignment' => 'center']);
-
- $table->addRow(100);
- $table->addCell(3000)->addText('G:'.$v['option_G'], 'cStyle');
- $table->addCell(3000)->addText($v['sel_G'], 'cStyle', ['alignment' => 'center']);
- $table->addCell(3000)->addText($v['percent_G'].'%', 'cStyle', ['alignment' => 'center']);
-
- $section->add($table);
-
- // 换行
- $section->addTextBreak(1);
- }
-
- // 先统计当前文件夹下文件的数量,当超过5个的时候,就全部删除再去下载
- $files = glob($_SERVER['DOCUMENT_ROOT'].'/uploads/docs/*');
- $file_count = count($files);
- if ($file_count >= 5) {
- foreach ($files as $file) {
- if (is_file($file)) {
- unlink($file);
- }
- }
- }
-
- // 保存到服务器
- $objWriter = IOFactory::createWriter($phpWord,'Word2007' );
- // 保存 Word 文档到指定路径
- $savePath1 = '/uploads/docs/'.$docxname.'.docx';
- $savePath = $_SERVER['DOCUMENT_ROOT'].'/uploads/docs/'.$docxname.'.docx';
- $objWriter->save($savePath);
-
- return apiResponse('200','success',$savePath1);
- } catch (Exception $e) {
-
- return apiResponse('110','error');
- }
- }
1、前端:先使用按钮事件,在点击事件里去请求后端返回的word文件的地址(这个地址是/uploads/docs/xxx.docx,而不是从系统目录开始);再使用JQ去触发a链接事件,注意a链接里必须有子元素(这里是span),通过子元素去触发链接
2、后端:上面info、list是从数据库查出来的数据,其中list是要导出的数据,这里是二维数组。先把文件保存到服务器上,再把word地址返回给前端,在前端通过a链接事件去下载导出。由于每导出一个文件都会保留在服务器上一份,长此以往文件会越来越多,所以只保留最近5份,如果文件数量超过5个就全部删除,再执行下载操作。