ThinkPHP使用phpword读取模板word文件并添加表格

发布于:2025-03-04 ⋅ 阅读:(14) ⋅ 点赞:(0)

 1.安装phpword包composer require phpoffice/phpword

2.模板文件结构

如上图框住的是要替换的文本和要复制表格样式

实现代码

<?php

namespace app\api\logic;

use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use PhpOffice\PhpWord\TemplateProcessor;
class Word
{

    public static function test($arr,$title,$stu_name)
    {
        //多行数据参考<w:br/>用于换行
//        $arr = [
//            ['id' => '1', 'value' => '单词内容<w:br/>单词内容<w:br/>单词内容单词内容单词内容单<w:br/>词内容单词内容单词内容单词内容单词内容单<w:br/>词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容单词内容'],
//            ['id' => '2', 'value' => '单词内容单词内容单词内<w:br/>容单词内容单词内容'],
//            ['id' => '3', 'value' => '单词内容单词<w:br/>内容单词内容单词内容单词内容'],
//            ['id' => '4', 'value' => '单词内容单词内容单<w:br/>词内容单词内容单词内容单词内容单词内容单<w:br/>词内容单词内容单词内容<w:br/>单词内容单词内容单词内容单词内容单词内容'],
//            ['id' => '5', 'value' => '单<w:br/>词<w:br/>内<w:br/>容'],
//        ];

        //新文件名
        $filename = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).".docx";
        $date = date('Y-m-d');
        $path = "export/word/$date/";
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        //实例化, 参数传入模板文件地址
        $word_template = ROOT_PATH.'public/export/test.docx'; // 使用绝对路径

        // 检查模板文件是否存在
        if (!file_exists($word_template)) {
            throw new \Exception("模板文件不存在: " . $word_template);
        }
        $templateProcessor = new TemplateProcessor($word_template);
        //替换(设置)变量值
        $array_title = [
            'title' => $title,
            'date' => $date,
            'num' => count($arr),
            'name' => $stu_name,
        ];
        $templateProcessor->setValues($array_title);


        //生成表格
        $table = new Table(['borderSize' => 12, 'width' => 6000, 'unit' => TblWidth::TWIP, 'alignMent' => 'center']);

        $rows = count($arr);//总行数
        $templateProcessor->cloneRow('id', $rows);//$arr条数复制行
        for ($i = 0; $i < $rows; $i++) {
            $templateProcessor->setValue("id#" . ($i + 1), $arr[$i]['id']);//替换变量
            $templateProcessor->setValue("value#" . ($i + 1), $arr[$i]['value']);//替换变量
        }
        $templateProcessor->setComplexBlock('table', $table);
        //保存文件
        $templateProcessor->saveAs($path . $filename);
        return "/" . $path . $filename;
    }


}

上图是最终生成的word文件