thinkphp使用phpword生成word文档自动下载 有图片

时间:2020-01-07
本文章向大家介绍thinkphp使用phpword生成word文档自动下载 有图片,主要包括thinkphp使用phpword生成word文档自动下载 有图片使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我给封装成函数了  加一些注释

function expordWord($data,$title)
 {
     vendor("PHPWord.PHPWord");
            // New Word Document
        $PHPWord = new \PHPWord();
        header("Content-Type: text/html; charset=UTF-8");
 
        $PHPWord->addFontStyle('rStyle', array('bold' => true, 'italic' => true, 'size' => 12));//定义样式
        $PHPWord->addParagraphStyle('pStyle', array('align' => 'center', 'spaceAfter' => 100));
        $PHPWord->addTitleStyle('titlestyle', array('bold' => true,'size' => 16),array('spaceAfter' => 240,'align' => 'center'));//标题的样式


        $section = $PHPWord->createSection();//创建新页面


 
        $section->addTitle($title,'titlestyle');
        $section->addTextBreak(2);
        
        foreach($data as $k=>$v) {
            $section->addText('题号:'.$v['no'],'rStyle');
            $section->addImage($v['pimg'], array('width'=>500, 'height'=>90));
            $section->addTextBreak(2);
            
            $section->addText('答案:');
            $section->addImage($v['aimg'], array('width'=>500, 'height'=>90));
            
            $section->addTextBreak(4);
        }
    
         $xlsTitle = iconv('utf-8', 'gb2312');//文件名称
         $fileName = $_SESSION['account'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
          header('pragma:public');
          header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$xlsTitle.'.docx"');
          header("Content-Disposition:attachment;filename=$fileName.docx");//attachment新窗口打印inline本窗口打印
          header( 'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
          ob_clean();//关键
          flush();//关键
          $objWrite = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
          $objWrite->save('php://output');
          exit;
 }

调用

   public function test()
    {
             
        $data=array(
        0=>array('no'=>1,'pimg'=>'./uploads/questionanswer/2019-12-07/5deb1c575125d_a_1575706883819_0.jpg','aimg'=>'./uploads/questionanswer/2019-12-07/5deb1c575125d_a_1575706883819_0.jpg'),
        1=>array('no'=>2,'pimg'=>'./uploads/questionanswer/2019-12-07/5deb1c575125d_a_1575706883819_0.jpg','aimg'=>'./uploads/questionanswer/2019-12-07/5deb1c575125d_a_1575706883819_0.jpg'),
        );

         expordWord($data,'试卷名称');
 
    }

 

样子

$flag 上一页 下一页