PHP导出word【 直接生成word文件 】

 使用composer安装PHPword:

composer require phpoffice/phpword

 直接生成word文件:

    public function makePhpWord()
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        //设置默认样式
        $phpWord->setDefaultFontName('宋体');//字体
        $phpWord->setDefaultFontSize(12);//字号
        //添加页面
        $section = $phpWord->createSection();
        $phpWord->addFontStyle('rStyle', array('bold'=>true,'color'=>'87CEEB','size'=>35));
        $phpWord->addParagraphStyle('pStyle', array('align'=>'center','spacing'=>120));
        $refund_map['tkid'] = (string)$tkid;
        $table_find_obj = Mongodb::table('table')->find();
        if(!$table_find_obj){
            return false;
        }
        $fontStyle = array('color'=>'000000', 'size'=>15,'align'=>'center');
        $phpWord->addFontStyle('myOwnStyle', $fontStyle);
        $section->addText('名称:11', 'myOwnStyle');
        $section->addTextBreak(1);
        $section->addText('产品:22', 'myOwnStyle');
        $section->addTextBreak(1);
        $imageStyle = array('width'=>100, 'height'=>80, 'align'=>'center');
        $section->addText(iconv('utf-8', 'gb2312','身份证正面:'), 'myOwnStyle');
        $section->addMemoryImage('',$imageStyle);$section->addMemoryImage($img,$imageStyle);
        $section->addTextBreak(1);

        $section->addPageBreak();//分页
        $xlsTitle = 'text_demo';//文件名称
        $fileName = 'text_demo'.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定    
        header('pragma:public');
        header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$xlsTitle.'.doc"');
        header("Content-Disposition:attachment;filename=$fileName.doc");//attachment新窗口打印inline本窗口打印
        header( 'Content-Type: image/jpeg');
        ob_clean(); // 解决文件损坏
        flush(); // 关键
        $objWrite = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWrite->save('php://output');
        exit;

    }

辅助链接:

https://github.com/PHPOffice/PHPWord

你可能感兴趣的:(PHP)