温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用PHPWord生成word文档

发布时间:2021-05-17 16:58:09 来源:亿速云 阅读:354 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关如何使用PHPWord生成word文档,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

安装

我们使用Composer 来安装PHPWord。

composer require phpoffice/phpword

如何使用

自动加载

安装好phpword后,新建一个php文档,引入autoload.php。

require 'vendor/autoload.php';

实例化

实例化并新增一个空白页。

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();

添加文字内容

向空白页添加文字内容,可以设置文字的样式,包括字体、颜色、字号、粗体等等。

$fontStyle = [
  'name' => 'Microsoft Yahei UI',
  'size' => 20,
  'color' => '#ff6600',
  'bold' => true
];
$textrun = $section->addTextRun();
$textrun->addText('你好,这是生成的Word文档。 ', $fontStyle);

链接

可以为Word文档中的文字添加用于点击跳转的链接。

$section->addLink('https://www.helloweba.net', '欢迎访问Helloweba', array('color' => '0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));
$section->addTextBreak();

图片

可以在word中添加图片,如图片地址logo.png,尺寸为64x64。图片源也可以是远程图片。

$section->addImage('logo.png', array('width'=>64, 'height'=>64));

页眉

为Word文档添加页眉。

$header = $section->addHeader();
$header->addText('Subsequent pages in Section 1 will Have this!');

页脚

为word文档添加页脚,页脚内容是页码,格式居中。

$footer = $section->addFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', null, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER));

增加一页

继续增加一页,加入内容。

$section = $phpWord->addSection();
$section->addText('新的一页.');

表格

增加一个基础表格,可以设置表格的样式。

$header = array('size' => 16, 'bold' => true);
$rows = 10;
$cols = 5;
$section->addText('Basic table', $header);
$table = $section->addTable();
for ($r = 1; $r <= 8; $r++) {
  $table->addRow();
  for ($c = 1; $c <= 5; $c++) {
    $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
  }
}

生成Word文档

如果你想生成word文档放在服务器上,可以使用:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('hellwoeba.docx');

下载Word文档

如果你想直接下载Word文档,不在服务器上保存的话,可以使用:

$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 = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");

关于如何使用PHPWord生成word文档就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI