需求:最近做一个word新闻规范扫描的工具,需要将wold中的内容读取出来扫描可疑、错误词文本,并将错误可疑文本添加背景颜色。
内容扫描规范识别不在本文中描述,
重点
说怎样通过
编程语言
操作word实现文字添加背景色
。
为了能快速达到效果,直接在
https://github.com/PHPOffice/...
这个项目上扩展的功能:
-
在路径 phpoffice/phpword/src/PhpWord/ 中新建文件 Template.php
namespace PhpOffice\PhpWord;
class Template extends TemplateProcessor
public $tempDocumentMainPart;
public function __construct($documentTemplate)
parent::__construct($documentTemplate);
static $wordArr;
static $color = 'yellow';
* 多个词替换目前替换背景色功能
* @param $word
* @param $color
* @example {
* $template = new \PhpOffice\PhpWord\Template($path);
* $template->setWordBgColor($txt, 'yellow');
public function setWordArrBgColor($word, $color)
self::$wordArr = array_unique($word);
if (!empty(self::$wordArr)) {
self::$color = $color;
$this->tempDocumentHeaders = $this->_replace($this->tempDocumentHeaders);
$this->tempDocumentMainPart = $this->_replace($this->tempDocumentMainPart);
$this->tempDocumentFooters = $this->_replace($this->tempDocumentFooters);
private function _replace($content) {
return preg_replace_callback(
'/<w:r w:([^>]*)>((?:(?!<\w:r>)[\s\S])*)<w:t[^>]*>((?:(?!<\/w:r>)[\s\S])*)<\/w:t><\/w:r[^>]*>/iUs',
function ($matches) {
// print_r($matches);
if (!empty(trim($matches[3]))) {
$text = $matches[3];
foreach (self::$wordArr AS $value) {
// 判断关键词在字符串中是否存在
if (false !== strpos($text, $value)) {
// 背景色属性
$bgAttr = empty($matches[2])
? '<w:rPr><w:highlight w:val="'.self::$color.'"/></w:rPr>'
: str_ireplace('</w:rPr>', '<w:highlight w:val="'.self::$color.'"/></w:rPr>', $matches[2]);
$matches[0] = str_ireplace($value,
'</w:t></w:r><w:r w:'.$matches[1].'>'.$bgAttr.'<w:t>'.$value.'</w:t></w:r><w:r w:'.$matches[1].'>'.$bgAttr.'<w:t>',
$matches[0]);
if (!empty($matches[0])) {
// 过滤掉空的
$matches[0] = preg_replace('/<w:r w:[^>]*>(?:(?!<\w:t>)[\s\S])*<w:t[^>]*><\/w:t><\/w:r[^>]*>/iUs', '', $matches[0]);
return $matches[0];
$content);
//引入类库
require autoload.php
$path = './test.docx';
$template = new \PhpOffice\PhpWord\Template($path);
$template->setWordArrBgColor(['TMD', '台湾省', 'Caonima'], 'yellow');
需求:最近做一个word新闻规范扫描的工具,需要将wold中的内容读取出来扫描可疑、错误词文本,并将错误可疑文本添加背景颜色。内容扫描规范识别不在本文中描述,重点说怎样通过编程语言操作word实现文字添加背景色。为了能快速达到效果,直接在https://github.com/PHPOffice/... 这个项目上扩展的功能:下载项目...
use
Php
Office
\
Php
Spreadsheet\Reader\Xlsx;
use
Php
Office
\
Php
Spreadsheet\Spreadsheet;
//导出处理
$obj
PHP
Excel = new Spreadsheet();
$obj
PHP
Excel->setActiveSheetIndex(0);
//水平居中对齐样式
$styleCenterArray = [
'alignment' => [
'horizontal' => \Ph.
PHP
WORD
实现
单元格内同一行文字设置不同的样式比如不同颜色不同大小粗细是否斜体等等
PHP
WORD
这个问题困扰了我好几天,做过
PHP
Excel的
实现
方法,在
PHP
Excel中内置了富文本对象,直接创建就可以了,可以参考我另写的一篇
PHP
Excel的文章
在
PHP
WORD
里没有提供富文本对象的功能,所以它的表格的某个单元格内没有办法采用富文本对象的方式,按照文本框的方式理论上要想
实现
的话采用:
$cell = $table->addCell(2000);
$catname = $cell->
$sheet->setCellValue('A1','你好')->getStyle('A1')->getAlignment()->setHorizontal(\
Php
Spreadsheet\Style\Alignment::HORIZONTAL_CENTER);
//自动设置行宽(没有合并列下)
$sheet->setCellValue('A','...