欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > ThinkPHP使用phpword读取模板word文件并添加表格

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

2025/3/1 16:41:47 来源:https://blog.csdn.net/qq_40088333/article/details/145924216  浏览:    关键词:ThinkPHP使用phpword读取模板word文件并添加表格

 1.安装phpword包composer require phpoffice/phpword

2.模板文件结构

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

实现代码

<?phpnamespace 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文件

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词