C# 设置Word指定文字、段落背景色

 时间:2024-10-14 02:30:32

此条经验将分享通过C#编程来实现给Word文档中的指定文字或者段落设置背景色。

工具/原料

Free Spire.Doc for .NET(免费版)

Visual Studio

dll引用

1、可通过E-iceblue或Nuget官网下载安装Free Spire.Doc for .NET后,注意在项目程序中添加引用Spire.Doc.dll(dll文件可在安装路径下的Bin文件夹中获取)。

C# 设置Word指定文字、段落背景色

C# 代码示例(供参考)

1、using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;using System.Drawin爿讥旌护g;namespace TextBackgroudColor_Doc{ class Program { static void Main(string[] args) { //创建Document实例并加载示例文档 Document document = new Document(); document.LoadFromFile("test.docx"); //获取第1段落,并为其设置底色 Paragraph paragaph = document.Sections[0].Paragraphs[0]; paragaph.Format.BackColor = Color.YellowGreen; //为第2段里查找的特定文字添加底色 paragaph = document.Sections[0].Paragraphs[1]; TextSelection selection = paragaph.Find("江户川乱步奖", false, true); TextRange range = selection.GetAsOneRange(); range.CharacterFormat.TextBackgroundColor = Color.Yellow; //保存文档 document.SaveToFile("result.docx", FileFormat.Docx); System.Diagnostics.Process.Start("result.docx"); } }}

2、完成代码后,调试程序,生成文档。文档效果如下:

C# 设置Word指定文字、段落背景色
  • 勤哲excel服务器初级教程:[2]定义数据项
  • javascript(js)怎么获取属性和移除属性
  • 几种防水帆布材质 轻松搞定货物遮盖问题
  • LoadRunner如何新建脚本和解决方案?
  • 热门搜索
    芦笋怎么做好吃 腰肌劳损怎么恢复 快手怎么删除自己的作品 月经量少该怎么调理 基围虾怎么做好吃 枣核吞下去了怎么办 走向共和为什么禁播 藉怎么组词 跨境电商怎么做 show怎么读