本文已参与「新人创作礼」活动,一起开启掘金创作之路。
在开发项目中,遇到的需求:把后台录入的数据保存成word文档,以便其他人员使用。于是在调研的时候,从git上找了PHPWord。
一、安装PHPWord
环境需求:
- PHP 5.3.3+
- XML 解析器扩展
- Laminas Escaper组件
官方使用 Composer 来安装的,当然也可以基于git安装。
1、基于Composer安装
如图所示:
2、基于git安装
git地址为:github.com/PHPOffice/P…
可以在git环境下输入
git clone <https://github.com/PHPOffice/PHPWord.git>
等待下载完成可即完成插件的下载。
下载的文件及目录如下图所示:
以下是 PHPWord 库的基本示例。示例文件夹中提供了更多示例。
<?php
require_once 'bootstrap.php';
// Creating the new document...
$phpWord = new \PhpOffice\PhpWord\PhpWord();
/* Note: any element you append to a document must reside inside of a Section. */
// Adding an empty Section to the document...
$section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
);
/*
* Note: it's possible to customize font style of the Text element you add in three ways:
* - inline;
* - using named font style (new font style object will be implicitly created);
* - using explicitly created font style object.
*/
// Adding Text element with font customized inline...
$section->addText(
'"Great achievement is usually born of great sacrifice, '
. 'and is never the result of selfishness." '
. '(Napoleon Hill)',
array('name' => 'Tahoma', 'size' => 10)
);
// Adding Text element with font customized using named font style...
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
$fontStyleName,
array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
$section->addText(
'"The greatest accomplishment is not in never falling, '
. 'but in rising again after you fall." '
. '(Vince Lombardi)',
$fontStyleName
);
// Adding Text element with font customized using explicitly created font style object...
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('"Believe you can and you're halfway there." (Theodor Roosevelt)');
$myTextElement->setFontStyle($fontStyle);
// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');
// Saving the document as ODF file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('helloWorld.odt');
// Saving the document as HTML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('helloWorld.html');
/* Note: we skip RTF, because it's not XML-based and requires a different example. */
/* Note: we skip PDF, because "HTML-to-PDF" approach is used to create PDF documents. */
注意到实例的开头有这么一行代码
require_once 'bootstrap.php';
其中文件内容如下:
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors. test bootstrap
*
* @see https://github.com/PHPOffice/PHPWord
* @copyright 2010-2018 PHPWord contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
$vendorDirPath = realpath(__DIR__ . '/vendor');
if (file_exists($vendorDirPath . '/autoload.php')) {
require $vendorDirPath . '/autoload.php';
} else {
throw new Exception(
sprintf(
'Could not find file '%s'. It is generated by Composer. Use 'install --prefer-source' or 'update --prefer-source' Composer commands to move forward.',
$vendorDirPath . '/autoload.php'
)
);
}
当我们应用的时候,发现其检测vendor目录路径,并使用autoload.php文件,如果你通过git安装时却没有此文件夹以及其文件。
那么就需要我们通过 Composer单独生成。
3、生成vendor目录及autoload.php等文件
我使用的mac,并且环境中的composer 不可用,我使用的是 局部Composer方式来生成的目录及文件。
以下安装仅供参考:
// 注意 :先进到自己PHPWord 目录下
// 命令如下:
curl -sS https://getcomposer.org/installer | php
php composer.phar dump-autoload
如图所示:
然后回到自己的PHPWord目录下查看,目录和文件生成成功,如下图所示:
二、使用PHPWord
1、项目引入PHPWord
根据自己的项目情况引入
// 引入 PHPWord
define('WORD_PATH', dirname(__FILE__).'/../phplib/PHPWord/');
require_once WORD_PATH.'bootstrap.php';
2、把html转成word文档并支持下载
封装方法如下:
/**
* Function getWordFile
* 获取下载文档 【使用 PhpWord】 第一种 方法
* @access public
* @param bool $is_download 是否下载
* @return null
* @throws
* @author sunct
* @time 2022/5/11 下午3:10
* @since 1.0
*/
public function getWordFile($is_download = true){
$phpWord = new \PhpOffice\PhpWord\PhpWord;
$section = $phpWord->addSection();
$html = new \PhpOffice\PhpWord\Shared\Html;
// 获取 html 内容,根据自己实际情况修改即可
// $wordData = $this->getHtmlInfo();
$wordData = "<div style='margin-bottom: 20px;text-align: center;font-size:24px;font-weight: bold;font-family:微软雅黑, Microsoft YaHei, SimHei,Helvetica,sans-serif;'>测试使用PHPWord把html转成word文档并支持下载</div>
<div style='max-width:300px; text-align: left;'><img width='260' src='https://自己的图片地址/167E3E4119AFCF2E7D81999601F08C0B.jpg'/></div>";
//文档生成路径
$need_file_dir = self::$file_dir.$ds_name;
if (!is_dir($need_file_dir)) {
mkdir($need_file_dir, 0777, true);
chmod($need_file_dir,0777);
}
// addHtml 函数请阅读源码,其中,第四个参数是 有(远程)图片的时候使用。
$html::addHtml($section, $wordData, false, false,'IMG_SRC_SEARCH');
// 将内容保存为 word 文档
$file_name = "测试_".date("Y年m月d日H时i分s秒").".docx";
$filepath = $need_file_dir.'/'.$file_name;
$phpWord->save($filepath, 'Word2007');
// 是否要下载
if($is_download){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
}
}
调用封装的函数即可。
文件信息如下图所示:
生成的word文件内容如下图所示:
注意:html样式如果不生效,请查找官方文档即可。
完美!
END
如有问题请在下方留言。
或关注我的公众号“孙三苗”(sunsanmiao),输入“联系方式”。获得进一步帮助。