美文网首页
PHP导出word

PHP导出word

作者: dongshixiao | 来源:发表于2018-10-10 10:28 被阅读0次

    1.composer.json 文件添加

    "phpoffice/phpword": "v0.14.*",
    

    第一种是直接生成word文件,不建议使用该方式

    <?php
    /**
     * Created by PhpStorm.
     * User: season
     * Date: 2018/9/26
     * Time: 11:13
     */
    include_once './vendor/autoload.php';
    $phpWord = new PhpOffice\PhpWord\PhpWord();
    //设置默认样式
    $phpWord->setDefaultFontName('宋体');//字体
    $phpWord->setDefaultFontSize(12);//字号
    //添加页面
    $section = $phpWord->createSection();
    //标题
    $section->addText(
        '施工合同',
        [
            'name' => '仿宋_GB2312',
            'size' => 22,
            'bold' => true,
        ],
        [
            'align' => 'center'
        ]
    );
    $section->addTextBreak(3);//换行符
    $section->addText('订单编号:____', ['size' => 10.5,]);
    $section->addTextBreak();//换行符
    $section->addPageBreak();//分页符
    //生成的文档为Word2007
    $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $writer->save('./word/' . time() . '.docx');
    

    第二种是根据一个模板文件,进行参数的替换生成word文件(推荐)

    <?php
    /**
     * Created by PhpStorm.
     * User: season
     * Date: 2018/9/26
     * Time: 11:13
     */
    include_once './vendor/autoload.php';
    $template = new \PhpOffice\PhpWord\TemplateProcessor('./base.docx');
    $template->setValue('order_no','201355132321');
    $template->setValue('price','300.00');
    $template->saveAs('test.docx');
    $time =  time();
    $file ='./word/' . $time . '.docx';
    $html_file ='./word/' . $time . '.html';
    $template->saveAs($file);
    

    其中的order_no 和 price就是需要替换的参数
    在word文件中使用 ${order_no}


    word文件中的参数标准

    相关文章

      网友评论

          本文标题:PHP导出word

          本文链接:https://www.haomeiwen.com/subject/ewxpaftx.html