phpword模板替换并插入表格

//——————————————————————————————————————————————
//类库引用:
//use PhpOffice\PhpWord\Element\Table;
//use PhpOffice\PhpWord\SimpleType\TblWidth;
//use PhpOffice\PhpWord\TemplateProcessor;
//——————————————————————————————————————————————
//控制器方法:
public function test()
    {
        //行数
        $row_total = 2;
        //列数
        $column_total = 6;
        $filename = "sj.docx";
        $date = date('Ymd');
        $path = "uploads/word/$date/";
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        //实例化, 参数传入模板文件地址
        $word_template = "assets/mb.docx";
        $templateProcessor = new TemplateProcessor($word_template);
        //替换(设置)变量值
        $arr1 = [
            'headline' => "2020-2021 学年度XXX学校1月月考试卷",
            'title' => "试卷副标题",
            'syllabus' => "考试范围:XXXX;考试时间:100分钟;命题人:XXX",
            'attention' => "注意事项:1.答题前填写好自己的姓名、班级、考号等信息2.请将正确答案填写在答题卡上",
        ];
        $templateProcessor->setValues($arr1);
        //生成表格
        $table = new Table(['borderSize' => 12, 'width' => 6000, 'unit' => TblWidth::TWIP, 'alignMent' => 'center']);
        for ($r = 0; $r < $row_total; $r++) {
            $table->addRow();
            for ($c = 0; $c < $column_total; $c++) {
                if ($r == 0) {
                    if ($c == 0) {
                        $str = "题号";
                    } else {
                        $str = $c;
                    }
                } else {
                    if ($c == 0) {
                        $str = "得分";
                    } else {
                        $str = "";
                    }
                }
                $table->addCell(150)->addText($str);
            }
        }
        $templateProcessor->setComplexBlock('table', $table);
        //保存文件
        $templateProcessor->saveAs($path . $filename);
        return "/" . $path . $filename;
    }

模板:
phpword模板替换并插入表格_第1张图片
处理后:
phpword模板替换并插入表格_第2张图片

你可能感兴趣的:(php)