利用PHPWord不使用模板纯代码生成Word

54次阅读
没有评论

共计 1898 个字符,预计需要花费 5 分钟才能阅读完成。

简介

PHPWord 是一个用纯 PHP 编写的库,它提供了一组用于写入和读取不同文档文件格式的类。

项目地址:https://github.com/PHPOffice/PHPWord

使用

// 引入 PHPWord 类库
require '../vendor/autoload.php';
use \PhpOffice\PhpWord\PhpWord;

// 创建 Word 文档
$phpWord = new PhpWord();
// 设置默认字体和字号
$phpWord->setDefaultFontName('宋体');
$phpWord->setDefaultFontSize(14); // 四号字体
// 定义一级标题样式
$phpWord->addTitleStyle(1, ['size' => 16, 'bold' => true]); // 三号字体

// 添加段落
$section = $phpWord->addSection();
$section->addText('添加文本', ['size' => 18, 'bold' => true], ['alignment' => 'center', 'spaceAfter' => 240]);
$section->addTitle('添加标题', 1);
$section->addText('添加文本', null, ['spaceAfter' => 240]);

// 添加表格
$table = $section->addTable(['borderSize' => 7.5, 'cellMargin' => 100, 'layout'=> 'fixed']);
$table->addRow();
$table->addCell(1200, ['valign' => 'center'])->addText(" 列 1 ", ['size' => 10.5,'bold' => true],['alignment'=>'center']);
$table->addCell(2600,['valign' => 'center'])->addText(" 列 2 ", ['size' => 10.5,'bold' => true],['alignment'=>'center']);
$table->addCell(2600,['valign' => 'center'])->addText(" 列 3 ", ['size' => 10.5,'bold' => true],['alignment'=>'center']);
$table->addCell(2600,['valign' => 'center'])->addText(" 列 4 ", ['size' => 10.5,'bold' => true],['alignment'=>'center']);

$table->addRow();
$table->addCell(null, ['width'=>500])->addText(" 行 A ", ['size' => 10.5,'alignment' => 'both']);

$cell = $table->addCell();
$cell->addText(" 行 B ", ['size' => 10.5,'alignment' => 'both']);
$cell->addLink('https://www.baidu.com/', 'https://www.baidu.com/',array('color' => '0000FF','size' => 10.5, 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));

$info = '<w:br /> 行 C';
$cell = $table->addCell();
$textrun = $cell->addTextRun();
$textrun->addText('PMID:',['size'=>10.5]);
$textrun->addLink('https://www.baidu.com/', '百度', array('color' => '0000FF','size' => 10.5, 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));

$table->addCell()->addText(" 行 D ", ['size' => 10.5,'alignment' => 'both']);

// 保存文档
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('hello.docx');

正文完
 0
三毛笔记
版权声明:本站原创文章,由 三毛笔记 于2023-09-20发表,共计1898字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)