PHP使用phpWord生成Word文档
文章描述:
在很多时候我们会使用word文档来存储数据,那么怎么使用PHP来生成word文档来存储内容呢?
下载安装
下载phpWord扩展,这里使用composer来下载,使用composer切换到项目根目录,然后使用以下命令:
composer require phpoffice/phpword
生成word文档文件
1、加载核心类
require 'vendor/autoload.php';
2、实例化
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
3、设置字体、字号、颜色和文字内容
$fontStyle = [
'name' => 'Microsoft Yahei UI',
'size' => 20,
'color' => '#ff6600',
'bold' => true
];
$textrun = $section->addTextRun();
$textrun->addText('hello你好', $fontStyle);
4、设置文字内容和超链接
$section->addLink('https://www.baidu.com', '百度一下', array('color' => '0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));
$section->addTextBreak();
5、设置图片和大小
$section->addImage('like.jpg', array('width'=>64, 'height'=>64));
6、设置word文档页眉
$header = $section->addHeader();
$header->addText('这是word页眉');
7、设置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}");
}
}
保存和下载表格
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('hellwoeba.docx');
$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");
发布时间:2021/06/24
发表评论