• 【PHPWrod】使用PHPWord导出word文档


    目的:PHP通过PHPWord类库导出文件为word。

    开发语言及类库:ThinkPHP、PHPWord

    一、安装PHPWord类库

    项目根目录使用composer安装PHPWord,安装完成后会在vendor目录下生成phpoffice文件夹,就是PHPWord类库

    composer require phpoffice/phpword

    二、使用PHPWord导出word文件

    前端代码

    <button type="button" class="layui-btn layui-btn-normal word"><i class="fa fa-file-word-o" aria-hidden="true">i> 导出分析报告 Wordbutton>
    1. // 下载word
    2. $(".word").click(function () {
    3. var shijuan_id = GetQueryString('shijuan_id')
    4. var grade_id = GetQueryString('grade_id')
    5. $.ajax({
    6. url:"exportreport2",
    7. type:'get',
    8. dataType:'JSON',
    9. data:{shijuan_id:shijuan_id,grade_id:grade_id},
    10. success:function (res) {
    11. console.log(res)
    12. if (res.code == '200') {
    13. var index = layer.alert('导出成功,请点击下载!', {
    14. skin: 'layui-layer-lan' //样式类名
    15. ,closeBtn: 0
    16. , btn: ['下载'] //按钮
    17. }, function(){
    18. var downloadDom = $("");
    19. // 触发a链接点击事件
    20. downloadDom.find('span').click();
    21. setTimeout(function(){ layer.close(index); }, 500);
    22. });
    23. }else{
    24. layer.msg('导出失败,请重试~')
    25. }
    26. }
    27. })
    28. })

    PHP代码

    1. use PhpOffice\PhpWord\IOFactory;
    2. use PhpOffice\PhpWord\PhpWord;
    3. public function exportreport2()
    4. {
    5. $shijuan_id = trim(input('post.shijuan_id'));
    6. $grade_id = trim(input('post.grade_id'));
    7. try {
    8. // 班级、试卷信息
    9. $info = model('Shijuan')->getShijuanGradeInfo($shijuan_id,$grade_id);
    10. // 标题
    11. $title = $info['filename'].'_考试分析报告';
    12. // 文件名
    13. $docxname = $info['grade'].'_'.$info['year'].$info['season'].'_'.$info['filename'].'_考试分析报告'.date('YmdHis',time());
    14. // 分析报告 二维数组
    15. $list = model('Shijuan')->getStudyReport($shijuan_id,$grade_id);
    16. // 实例化
    17. $phpWord = new PhpWord();
    18. header("Content-Type: text/html; charset=UTF-8");
    19. $phpWord->addFontStyle('cStyle', array('size' => 12,'name' => 'msyh'));//内容样式
    20. $phpWord->addFontStyle('bStyle', array('size' => 12, 'bold' => true, 'name' => 'msyh'));//加粗样式
    21. $phpWord->addFontStyle('titlestyle', array('bold' => true,'size' => 16,'name' => 'msyh'));//标题的样式
    22. // 创建新页面
    23. $section = $phpWord->addSection();
    24. $section->addText($title,'titlestyle', ['alignment' => 'center']);
    25. $section->addTextBreak(1);
    26. $section->addText('班级:'.$info['grade'].'_'.$info['year'].$info['season'], 'cStyle', ['alignment' => 'right']);
    27. $section->addText('总人数:'.$info['student'].'; 已交卷:'.$info['cmit'], 'cStyle', ['alignment' => 'right']);
    28. $section->addText('导出时间: '.date('Y-m-d H:i:s',time()), 'cStyle', ['alignment' => 'right']);
    29. // 表格样式
    30. $styleTable = array( 'borderSize'=>6, 'alignment' => 'center','cellMargin'=>80);
    31. // 第一行样式
    32. $styleFirstRow = array('bgColor'=>'f2f2f2' );
    33. $phpWord ->addTableStyle('myOwnTableStyle',$styleTable,$styleFirstRow);
    34. foreach($list as $k=>$v) {
    35. $section->addText('【'.$v['type'].'】 第'.($k+1).'题: '.$v['title'],'cStyle');
    36. $section->addText('【正确答案】: '.$v['answer'],['alignment' => 'center'],'cStyle');
    37. $section->addText('【正确率】'.$v['percent'].'%; 【作答人数】: '.$v['cmit_num'].'人次',['color' => '009688'],'cStyle');
    38. // 添加表格
    39. $table = $section->addTable('myOwnTableStyle');
    40. //添加一行(addRow执行后才能使用addCell给本行添加列,括号内数字代表高度)
    41. $table->addRow(100);
    42. //表头添加(数字代表宽度,valign代表对齐方式)
    43. $table->addCell(3000)->addText('选项', 'bStyle', ['alignment' => 'center']);
    44. $table->addCell(3000)->addText('选择次数/人次','bStyle', ['alignment' => 'center']);
    45. $table->addCell(3000)->addText('比例', 'bStyle', ['alignment' => 'center']);
    46. // 选择题
    47. $table->addRow(100);
    48. $table->addCell(3000)->addText('A:'.$v['option_A'], 'cStyle');
    49. $table->addCell(3000)->addText($v['sel_A'], 'cStyle', ['alignment' => 'center']);
    50. $table->addCell(3000)->addText($v['percent_A'].'%', 'cStyle', ['alignment' => 'center']);
    51. $table->addRow(100);
    52. $table->addCell(3000)->addText('B:'.$v['option_B'], 'cStyle');
    53. $table->addCell(3000)->addText($v['sel_B'], 'cStyle', ['alignment' => 'center']);
    54. $table->addCell(3000)->addText($v['percent_B'].'%', 'cStyle', ['alignment' => 'center']);
    55. $table->addRow(100);
    56. $table->addCell(3000)->addText('C:'.$v['option_C'], 'cStyle');
    57. $table->addCell(3000)->addText($v['sel_C'], 'cStyle', ['alignment' => 'center']);
    58. $table->addCell(3000)->addText($v['percent_C'].'%', 'cStyle', ['alignment' => 'center']);
    59. $table->addRow(100);
    60. $table->addCell(3000)->addText('D:'.$v['option_D'], 'cStyle');
    61. $table->addCell(3000)->addText($v['sel_D'], 'cStyle', ['alignment' => 'center']);
    62. $table->addCell(3000)->addText($v['percent_D'].'%', 'cStyle', ['alignment' => 'center']);
    63. $table->addRow(100);
    64. $table->addCell(3000)->addText('E:'.$v['option_E'], 'cStyle');
    65. $table->addCell(3000)->addText($v['sel_E'], 'cStyle', ['alignment' => 'center']);
    66. $table->addCell(3000)->addText($v['percent_E'].'%', 'cStyle', ['alignment' => 'center']);
    67. $table->addRow(100);
    68. $table->addCell(3000)->addText('F:'.$v['option_F'], 'cStyle');
    69. $table->addCell(3000)->addText($v['sel_F'], 'cStyle', ['alignment' => 'center']);
    70. $table->addCell(3000)->addText($v['percent_F'].'%', 'cStyle', ['alignment' => 'center']);
    71. $table->addRow(100);
    72. $table->addCell(3000)->addText('G:'.$v['option_G'], 'cStyle');
    73. $table->addCell(3000)->addText($v['sel_G'], 'cStyle', ['alignment' => 'center']);
    74. $table->addCell(3000)->addText($v['percent_G'].'%', 'cStyle', ['alignment' => 'center']);
    75. $section->add($table);
    76. // 换行
    77. $section->addTextBreak(1);
    78. }
    79. // 先统计当前文件夹下文件的数量,当超过5个的时候,就全部删除再去下载
    80. $files = glob($_SERVER['DOCUMENT_ROOT'].'/uploads/docs/*');
    81. $file_count = count($files);
    82. if ($file_count >= 5) {
    83. foreach ($files as $file) {
    84. if (is_file($file)) {
    85. unlink($file);
    86. }
    87. }
    88. }
    89. // 保存到服务器
    90. $objWriter = IOFactory::createWriter($phpWord,'Word2007' );
    91. // 保存 Word 文档到指定路径
    92. $savePath1 = '/uploads/docs/'.$docxname.'.docx';
    93. $savePath = $_SERVER['DOCUMENT_ROOT'].'/uploads/docs/'.$docxname.'.docx';
    94. $objWriter->save($savePath);
    95. return apiResponse('200','success',$savePath1);
    96. } catch (Exception $e) {
    97. return apiResponse('110','error');
    98. }
    99. }

    1、前端:先使用按钮事件,在点击事件里去请求后端返回的word文件的地址(这个地址是/uploads/docs/xxx.docx,而不是从系统目录开始);再使用JQ去触发a链接事件,注意a链接里必须有子元素(这里是span),通过子元素去触发链接

    2、后端:上面info、list是从数据库查出来的数据,其中list是要导出的数据,这里是二维数组。先把文件保存到服务器上,再把word地址返回给前端,在前端通过a链接事件去下载导出。由于每导出一个文件都会保留在服务器上一份,长此以往文件会越来越多,所以只保留最近5份,如果文件数量超过5个就全部删除,再执行下载操作。

    上一篇:【TCPDF】使用TCPDF导出PDF文件icon-default.png?t=N7T8https://blog.csdn.net/qq_25285531/article/details/132761994?spm=1001.2014.3001.5502 

  • 相关阅读:
    2023年中国大学生留学现状及未来发展规划分析:直接就业仍是毕业后的主流选择[图]
    c++ 编译过程杂记等
    私有化轻量级持续集成部署方案--07-私有NPM仓库-Verdaccio
    面对全球新能源汽车合作发展创维汽车如何实现共赢
    Base64、Blob、File 三种类型的相互转换 最详细
    Android 自定义横向时间轴
    算法通过村第十关-并归|黄金笔记|手撕并归排序
    ⭐️【实用】Mybatis入门&使用
    互联网摸鱼日报(2022-12-07)
    antd前端上传获取文件的md5, 并结果form表单提交
  • 原文地址:https://blog.csdn.net/qq_25285531/article/details/132799282