版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zch3210/article/details/86228651
下载第三方类库
composer require phpoffice/phpword
<?php
namespace app\index\controller;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use think\Controller;
class Test extends Controller
{
public function getword()
{
$phpWord = new PhpWord();
//添加一个空白页
$section = $phpWord->addSection();
//添加目录
$styleTOC= array('index' => 500);
$styleFont= array('spaceAfter' => 60, 'name' => 'Tahoma', 'size' => 12);
$section->addTOC($styleFont, $styleTOC);
$fontstyle = [
'name' => '宋体',
'size' => 20,
'color' => 'red'
];
$textrun = $section->addTextRun();
$textrun->addText('你好,这是生成的Word文档', $fontstyle);
//添加换行
$section->addTextBreak(5);
$section->addText('123456');
//添加页眉
$header = $section->addHeader();
$header->addText('页眉');
//添加页脚
$footer = $section->addFooter();
$footer->addPreserveText('页脚', ['size' => 10], ['align' => 'center']);
$footer->addPreserveText('{PAGE}', null, ['align' => 'center']);
//添加新的一页
$section = $phpWord->addSection();
$section ->addText('新的一页');
//设置标题
$phpWord->addTitleStyle('1', ['size' => 15]);
$phpWord->addTitleStyle('2', ['size' => 13]);
$section->addTitle('标题1', 1);
$section->addTitle('标题2', 2);
$file = 'test.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
}
}