1、通过模板生成,最好使用.docx的文件生成否则会有权限问题
word内容

//模板的路径$path='./Public/File/模板.docx';//生成word路径$filePath= './Public/File/生成文件.docx';//声明一个模板对象、读取模板$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);// 替换模板中的变量,对应word里的 ${year}$templateProcessor->setValue('year',date('Y'));//年份$templateProcessor->setValue('lesson_head','张三');//姓名$templateProcessor->setValue('plan','十三五');//计划//生成新的word$templateProcessor->saveAs($filePath);
2、通过代码生成
//声明一个phpword对象$phpWord = new \PhpOffice\PhpWord\PhpWord();//声明一个页面,用来存放页面的内容,相当于一个容器$section = $phpWord->addSection();//添加一个段落文字$section->addText('123 4567');//声明普通文字,不同段落文字,可以在后面追加文字$textrun = $section->addTextRun();//添加文字$textrun->addText('123 ');//再上面内容的后面追加文字$textrun->addText('4567');//文字换行,参数可以控制换行的行数$textrun->addTextBreak(1);//段落文字换行,参数可以控制换行的行数$section->addTextBreak(1);//文字样式,可以指定许多样式,具体可以参考文档字体样式$textrun->addText('测试',array('size'=>18,'bold'=>true,'name'=>'宋体'));//生成Word文档$filePath= 'public/test.docx';$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');$objWriter->save($filePath);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号