ddddd

phpword使用整理

作者:程序员11 时间:2023-11-03 人气:114 QQ交流群\邮箱:1003265987@qq.com
phpword使用整理
要展示的内容

介绍

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

安装效果

image.png

创建文档

$phpWord = new PhpOfficePhpWordPhpWord();
 
// 向文档添加任何元素都必须先添加 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 PhpOfficePhpWordStyleFont();
$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);

效果:

image.png


换行符

可设置行数

$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');

效果:

image.png


创建表格

表格样式

$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']);
}

效果:

image.png

添加图片

$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');

效果:

image.png


文件保护

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

$documentProtection = $phpWord->getSettings()->getDocumentProtection();
$documentProtection->setEditing(PhpOfficePhpWordSimpleTypeDocProtect::READ_ONLY);
$documentProtection->setPassword('123456');

加载word文件

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

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

内容转化为html

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

保存

保存为DOCX

$objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('test.docx');

保存为ODF

$objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('test.odt');

保存为HTML

$objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('test.html');

直接下载

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

// 创建新的文档...
$phpWord = new PhpOfficePhpWordPhpWord();
$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 = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");

效果:

image.png

模板替换

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


格式

${XX}


加载模板

加载docx文档模板

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

替换字符串

模板内容


image.png

替换并保存

// 模板的路径
$path = 'template.docx';
// 声明一个模板对象、读取模板
$templateProcessor = new PhpOfficePhpWordTemplateProcessor($path);
 
// 替换模板中的变量,对应word里的 ${title}
$templateProcessor->setValue('title','简历');
$templateProcessor->setValue('name','张三');
$templateProcessor->setValue('gender','男');
 
// 生成word路径,根据自己的目录调整
$filePath= './test.docx';
// 生成新的word
$templateProcessor->saveAs($filePath);

效果:

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

image.png

替换图片

设置模板

image.png

简单替换

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

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

效果

image.png

设置图片属性

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

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

效果

image.png

替换表格

设置模板

image.png

设置表格数据

$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 PhpOfficePhpWordTemplateProcessor($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);

 效果

image.png

总结

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

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

参考

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

Welcome to PHPWord’s documentation — PHPWord 0.18.2 documentation

PHP使用phpword生成word文档 - 简


链接:https://blog.csdn.net/json_ligege/article/details/130993122


温馨提示:

欢迎阅读本文章,觉得有用就多来支持一下,没有能帮到您,还有很多文章,希望有一天能帮到您。

phpword使用整理---相关文章


评论区

ddddd

程序员-学习的网站-想学习编程的码农可以进来看看

首页

视频教程

购物车

我的订单