phpword使用整理

目录

介绍

安装

创建文档

设置默认字体和字号

设置文本样式

编号标题

换行符

分页符

超链接

创建表格

添加图片

文件保护

加载word文件

内容转化为html

保存

模板替换

格式

加载模板

替换字符串

替换图片

替换表格

总结

参考


介绍

PHPWord 是一个用纯 PHP 编写的库,它提供了一组用于写入和读取不同文档文件格式的类。PHPWord 的当前版本支持 Microsoft Office Open XML (OOXML 或 OpenXML)、 OASIS Open Document Format for Office Applications (OpenDocument 或 ODF)、 Rich Text Format (RTF)、 HTML 和 PDF。

安装

composer require phpoffice/phpword

安装效果

composer.json中新增一行

"phpoffice/phpword": "^1.0",

创建文档

$phpWord = new \PhpOffice\PhpWord\PhpWord();

// 向文档添加任何元素都必须先添加 Section
$section = $phpWord->addSection();

// 添加默认字体样式Text 元素
$section->addText(
    '正文内容正文内容正文内容正文内容正文内容正文内容正文内容正文内容正文内容'
);

设置默认字体和字号

文档的默认字体是Arial,字号为10号。可通过以下设置默认字体和字号:

$phpWord->setDefaultFontName('宋体');
$phpWord->setDefaultFontSize(10);

设置文本样式

可以通过三种方式自定义添加的Text元素的字体样式:

1.内联

// 设置段落样式:通过自定义内联字体
$section->addText(
    '段落1',
    array('name' => '宋体', 'size' => 30, 'bold' => true)
);

2.使用命名字体样式

将隐式创建新的字体样式对象

// 设置段落样式:通过使用命名字体样式自定义字体
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
    $fontStyleName,
    array('name' => '宋体', 'size' => 20, 'color' => 'red', 'bold' => true)
);
$section->addText(
    '段落3',
    $fontStyleName
);

3.使用显式创建的字体样式对象

// 设置段落标题:使用显式创建的字体样式对象自定义字体的Text元素
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('宋体');
$fontStyle->setSize(20);
$fontStyle->setColor('red');
$myTextElement = $section->addText('段落标题2');
$myTextElement->setFontStyle($fontStyle);

编号标题

定义编号样式和标题样式,并匹配两个样式,如下所示:

$phpWord->addNumberingStyle(
    'hNum',
    array('type' => 'multilevel', 'levels' => array(
        array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'),
        array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'),
        array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'),
        )
    )
);
$phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'hNum', 'numLevel' => 0, 'align' => 'center'));
$phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'hNum', 'numLevel' => 1));
$phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'hNum', 'numLevel' => 2));

$section->addTitle('标题1', 1);
$section->addTitle('标题2', 2);
$section->addTitle('标题3', 3);

效果:

换行符

可设置行数

$section->addTextBreak(1);

分页符

$section->addPageBreak();

超链接

将'HeadingN'段落样式应用于TextRun或Link。

$textrun = $section->addTextRun('Heading1');
$textrun->addText('The is ');
$textrun->addLink('https://blog.csdn.net/json_ligege', 'My Blog', 'Link');
// Link
$section->addLink('https://blog.csdn.net/json_ligege', 'CSDN', 'Link', 'Heading2');

效果:

 

创建表格

表格样式

$styleTable = array('borderSize' => 6, 'borderColor' => 'red', 'cellMargin' => 80);
// 定义表格样式
$phpWord->addTableStyle('table_1', $styleTable);

文字样式

$fontStyle = array('bold' => true, 'align' => 'center');

定义表格

$table = $section->addTable('table_1');

// 定义表格宽度
$width = 1000;
$table->addRow(40);
$table->addCell($width)->addText("ID", $fontStyle);
$table->addCell($width)->addText("名称", $fontStyle);
$table->addCell($width)->addText("性别", $fontStyle);
$table->addCell($width)->addText("年龄", $fontStyle);
$table->addCell($width)->addText("爱好", $fontStyle);

$arr = [
    ['id' => 1, 'name' => '张三', 'gender' => '男', 'age' => 18, 'hobby' => '足球'],
    ['id' => 2, 'name' => '张四', 'gender' => '女', 'age' => 18, 'hobby' => '跑步'],
    ['id' => 3, 'name' => '账务', 'gender' => '男', 'age' => 18, 'hobby' => '羽毛球'],
];

foreach ($arr as $k => $v) {
    $table->addRow();
    $table->addCell($width)->addText($v['id']);
    $table->addCell($width)->addText($v['name']);
    $table->addCell($width)->addText($v['gender']);
    $table->addCell($width)->addText($v['age']);
    $table->addCell($width)->addText($v['hobby']);
}

效果:

 

添加图片

$section->addImage('./images/word1.jpg', array(
    'width'         => 100,
    'height'        => 100,
    'marginTop'     => 100,
    'marginLeft'    => 100,
    'wrappingStyle' => 'behind'
));

添加水印图

$header = $section->addHeader();
$header->addWatermark('./images/word1.jpg');

添加文件对象

$section->addOLEObject('./test.cls');

效果:

 点击可打开excel文件

文件保护

文档(或其中的一部分)可以受密码保护。

$documentProtection = $phpWord->getSettings()->getDocumentProtection();
$documentProtection->setEditing(\PhpOffice\PhpWord\SimpleType\DocProtect::READ_ONLY);
$documentProtection->setPassword('123456');

加载word文件

可用来读取word文档内容,或者加载word模板
注意:只能读取docx文件,doc格式的文件无法读取。

$file = './uploads/contract/test.docx';
// 加载word文档,使用phpword处理
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);

内容转化为html

$xmlWriter  = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
$path = pathinfo($file);
$fileName =  './uploads/tmp/' . $path['filename'] . '.html';
$xmlWriter->save($fileName);

保存

保存为DOCX

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

保存为ODF

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('test.odt');

保存为HTML

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('test.html');

直接下载

使用php://output作为文件名。

// 创建新的文档...
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('文章正文文章正文文章正文文章正文');


$file = 'test.doc';
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");

效果:

模板替换

通过固定格式的字符串,来占位,通过加载模板后,进行变量替换。

格式

${XX}

加载模板

加载docx文档模板

// 模板的路径
$path = 'template.docx';
// 声明一个模板对象、读取模板
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);

替换字符串

模板内容

替换并保存

// 模板的路径
$path = 'template.docx';
// 声明一个模板对象、读取模板
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);

// 替换模板中的变量,对应word里的 ${title}
$templateProcessor->setValue('title','简历');
$templateProcessor->setValue('name','张三');
$templateProcessor->setValue('gender','男');

// 生成word路径,根据自己的目录调整
$filePath= './test.docx';
// 生成新的word
$templateProcessor->saveAs($filePath);

效果:

并不更改模板的样式,只是根据固定格式进行替换。

替换图片

设置模板

简单替换

只是简单替换,其他为图片默认。

$templateProcessor->setImageValue('img', ['path' => 'cover.jpg']);

效果

设置图片属性

可以在替换图片的基础上,设置一些图片属性。

$templateProcessor->setImageValue('img', [
    'path' => 'cover.jpg',
    'width'=>200,
    'height'=>200
]);

效果

 

替换表格

设置模板

设置表格数据

$arr = [
    ['id' => 1, 'name' => '龙傲天','class' => '一班', 'age' => '19', 'score' => 100],
    ['id' => 2, 'name' => '张武','class' => '二班', 'age' => '19', 'score' => 100],
    ['id' => 3, 'name' => '李云','class' => '三班', 'age' => '19', 'score' => 100],
    ['id' => 4, 'name' => '宋清','class' => '四班', 'age' => '19', 'score' => 100],
];

实现替换

// 模板的路径
$path = 'template.docx';
// 声明一个模板对象、读取模板
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);
// 复制行
$templateProcessor->cloneRow('id', count($arr));
// 替换变量
foreach ($arr as $k =>  $v) {
    $templateProcessor->setValue('id#' . ($k + 1), $v['id']);
    $templateProcessor->setValue('name#' . ($k + 1), $v['name']);
    $templateProcessor->setValue('class#' . ($k + 1), $v['class']);
    $templateProcessor->setValue('age#' . ($k + 1), $v['age']);
    $templateProcessor->setValue('score#' . ($k + 1), $v['score']);
}

// 生成word路径,根据自己的目录调整
$filePath = './test.docx';
// 生成新的word
$templateProcessor->saveAs($filePath);

 效果

总结

phpword功能很强大,无论是用来创建word文档还是使用word来做模板替换变量都可以很好的完成。可以用来做一些自动化的操作。

注意:对支持读取doc文档有些问题,需要一些配置还没有弄清楚。

参考

PHPWord插件创建表格及模板替换技术记录说明(含PHPWord文件及中文技术文档下载)-码代码-李雷博客

Welcome to PHPWord’s documentation — PHPWord 0.18.2 documentation

PHP使用phpword生成word文档 - 简

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JSON_L

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值