C#操作Word模擬解析HTML標記設(shè)置背景色詳解
需求
有如下由word.shape拼接九宮格圖表,通過模擬解析HTML文本可實現(xiàn)字體的設(shè)置,如圖中所示匹配度為9的標識為顏色為白色、字體加粗顯示,具體實現(xiàn)可參照我的文章《C# 操作Word模擬解析HTML標記輸出帶格式的文本》。新需求是需要改變文字Range對象所在的父對象的背景色,如下圖中匹配度為9的表格。

因此需要對HTML模擬解析進行進一步的改造設(shè)計,增加自定義屬性。
解決方案
目前主要針對如下兩個 Range 對象進行操作:
| 序號 | 對象 | 說明 |
| 1 | Word.Shape | 形狀對象,填充其背景色 |
基本的實現(xiàn)的思路如下:
一、將原始輸出文本按照指定的定義進行 HTML 標記化,如將 “匹配度9” 文本更改為 “<span style='font-weight:bold;color:#ffffff;parent-background-color:#4169E1;'>匹配度9</span>” (html 部分使用標準的 span + style ),這樣可以同時兼容標準的網(wǎng)頁版輸出。對 Range 的文本(Text)使用正則表達式提取 HTML 標記間的所有查找關(guān)鍵字。
二、對 Range 的字符集對象(Word.Characters)進行逐字操作,提取 HTML 標記的 style 屬性部分,分隔各種 style 進行解析,增加 background-color 背景色設(shè)置,重刷每一個字符的格式。并新增 parent-background-color 屬性,通過傳遞的參數(shù)對象,改變參數(shù)對象的背景填充色。
三、處理完格式設(shè)置,調(diào)用 Range.Find 對象替換掉 “多余” 的 HTML 標記文本,完成最終輸出效果。
范例運行環(huán)境
操作系統(tǒng): Windows Server 2019 DataCenter
操作系統(tǒng)上安裝 Office Word 2016
數(shù)據(jù)庫:Microsoft SQL Server 2016
.net版本: .netFramework4.7.1 或以上
開發(fā)工具:VS2019 C#
配置Office DCOM
配置方法可參照我的文章《C# 讀取Word表格到DataSet》進行處理和配置。
設(shè)計實現(xiàn)
組件庫引入

方法實現(xiàn)
processWordChars 方法基本說明如下表:
| 序號 | 參數(shù)名稱 | 參數(shù)類型 | 說明 |
|---|---|---|---|
| 1 | chars | Word.Characters | Word.Range的字符集對象 |
| 2 | ws | Word.Shape | 傳遞需要填充背景的形狀對象,默認值為 null |
方法示例代碼如下:
void processWordChars(Word.Characters chars,Word.Shape ws=null)
{
string content = chars.Parent.Text;
if (content == null || content == "") { return; }
Word.Find fnd = chars.Parent.Find;
ArrayList paras2 = new ArrayList();
paras2.Add(new string[] { "<span style=", "</span>" });
foreach (string[] p in paras2)
{
string pattern = string.Format(@"{0}(.*?){1}", p[0], p[1]);
System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(content, pattern);
foreach (System.Text.RegularExpressions.Match match in matches)
{
string key = match.Groups[1].Value; //提取的內(nèi)容
string vkey = key.Substring(key.IndexOf('>') + 1); //最終有效內(nèi)容
string vstyle = key.Substring(1, key.Length - vkey.Length - 3); //截取 style 值
string findkey = p[0] + key + "</span>"; //最終替換部分
int fk = content.IndexOf(findkey);
if (fk != -1)
{
for (int i = 1; i <= findkey.Length; i++)
{
foreach (string kv in vstyle.Split(';'))
{
string[] style = kv.Split(':');
if (style[0] == "color")
{
chars[fk + i].Font.Color =(Word.WdColor)ColorTranslator.ToOle(ColorTranslator.FromHtml(style[1]));
// 獲取ARGB值
}
else if(style[0]== "font-weight")
{
if (style[1] == "bold") {
chars[fk + i].Font.Bold=1;
}
}
else if (style[0] == "font-family")
{
chars[fk + i].Font.Name=style[1];
}
else if (style[0] == "background-color")
{
chars[fk + i].Font.Shading.BackgroundPatternColor = (Word.WdColor)ColorTranslator.ToOle(ColorTranslator.FromHtml(style[1]));
}
else if (style[0] == "parent-background-color")
{
if (ws != null)
{
ws.Fill.ForeColor.RGB = ColorTranslator.ToOle(ColorTranslator.FromHtml(style[1]));
}
}
}
}
fnd.ClearFormatting();
Object findText = findkey;
Object matchCase = false; Object matchWholeWord = Type.Missing; Object matchWildcards = false; Object matchSoundsLike = false; Object matchAllWordForms = false;
Object forward = true; Object wrap = Word.WdFindWrap.wdFindContinue; Object format = false;
Object replaceWith = vkey;
Object replace = Word.WdReplace.wdReplaceAll; Object matchKashida = Type.Missing; Object matchDiacritics = Type.Missing; Object matchAlefHamza = Type.Missing; Object matchControl = Type.Missing;
fnd.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,ref forward, ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
content = chars.Parent.Text;
}
}
}
}
小結(jié)
1、parent-background-color為自定義特殊屬性,不屬于標準屬性,代碼增加了對該屬性值的處理,并配合傳遞的 Word.Shape 對象。
2、背景顏色請參照十六進制表示輸入(如 #00ff00)。
3、示例代碼中 Word 表示 using Word=Microsoft.Office.Interop.Word; 的引用。
到此這篇關(guān)于C#操作Word模擬解析HTML標記設(shè)置背景色詳解的文章就介紹到這了,更多相關(guān)C#設(shè)置Word背景色內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# Windows API應(yīng)用之基于FlashWindowEx實現(xiàn)窗口閃爍的方法
這篇文章主要介紹了C# Windows API應(yīng)用之基于FlashWindowEx實現(xiàn)窗口閃爍的方法,結(jié)合實例形式分析了Windows API函數(shù)FlashWindowEx的功能、定義及實現(xiàn)窗口閃爍的相關(guān)技巧,需要的朋友可以參考下2016-08-08
C#結(jié)合Spire.Doc for .NET實現(xiàn)智能復(fù)制Word文檔內(nèi)容
在日常的開發(fā)工作或文檔處理中,我們常常需要將一個Word文檔中的內(nèi)容復(fù)制到另一個文檔,本文將為您揭示如何利用C#編程語言與強大的Spire.Doc for .NET庫,實現(xiàn)Word文檔內(nèi)容的智能復(fù)制,感興趣的小伙伴可以了解下2026-01-01
總結(jié)C#刪除字符串數(shù)組中空字符串的幾種方法
C#中要如何才能刪除一個字符串數(shù)組中的空字符串呢?下面的文章會介紹多種方式來實現(xiàn)清除數(shù)組中的空字符串,以及在.net中將字符串數(shù)組中字符串為空的元素去除。2016-08-08
C#使用zxing/zbar/thoughtworkQRcode解析二維碼的示例代碼
zxing是谷歌開源的二維碼庫,zbar,thoughtworkQRcode也是開源的,三者之間比較各有優(yōu)劣,本文將通過一個案例demo源碼,帶來認識學(xué)習(xí)下這三者的實際解碼效果,感興趣的可以了解一下2023-07-07

