Aspose.Words for .NET 教程(六):文本处理与格式化全攻略

作者:微信公众号:【架构师老卢】
9-22 16:33
6

Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847

第六章 文本处理详解

在 Aspose.Words for .NET 中,文本操作 是最常见的功能之一。无论是插入与删除、查找替换,还是格式化与多语言处理,Aspose.Words 都提供了灵活的 API。


6.1 文本插入与删除

使用 DocumentBuilder 可以方便地插入文本;删除文本可以通过修改节点内容或清除文档段落来实现。

📌 示例:插入与删除文本

using Aspose.Words;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 插入文本
builder.Writeln("这是第一段文字。");
builder.Writeln("这是第二段文字。");

// 删除第一段的内容
doc.FirstSection.Body.FirstParagraph.RemoveAllChildren();

doc.Save("text-insert-delete.docx");

6.2 查找与替换功能

Aspose.Words 提供 Range.Replace 方法,可以替换文档中的指定文本。

📌 示例:简单替换

using Aspose.Words;

Document doc = new Document("input.docx");

// 将 "Aspose" 替换为 "Aspose.Words"
doc.Range.Replace("Aspose", "Aspose.Words", new FindReplaceOptions());

// 保存结果
doc.Save("text-replace.docx");

6.3 正则表达式查找替换

支持 正则表达式 (Regex) 查找与替换,更灵活地处理复杂文本。

📌 示例:替换邮箱地址

using System.Text.RegularExpressions;
using Aspose.Words;

Document doc = new Document("input.docx");

// 用 "[已隐藏]" 替换所有邮箱地址
Regex regex = new Regex(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}");
doc.Range.Replace(regex, "[已隐藏]", new FindReplaceOptions());

doc.Save("text-regex.docx");

6.4 文本格式化与样式应用

可以为插入的文本应用字体、颜色、对齐方式等格式化设置。

📌 示例:加粗、设置颜色和对齐

using Aspose.Words;
using System.Drawing;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 设置格式
builder.Font.Bold = true;
builder.Font.Color = Color.DarkBlue;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

builder.Writeln("这是加粗并居中的蓝色文字");

doc.Save("text-format.docx");

6.5 字体设置与文字效果

可以控制字体大小、样式(粗体/斜体/下划线)、文字阴影等效果。

📌 示例:字体设置

using Aspose.Words;
using System.Drawing;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 设置字体
builder.Font.Name = "Arial";
builder.Font.Size = 16;
builder.Font.Italic = true;
builder.Font.Underline = Underline.Dash;
builder.Font.Shadow = true;

builder.Writeln("这是带阴影的斜体文字");

doc.Save("text-font.docx");

6.6 多语言文本处理

Aspose.Words 支持多语言文本,包括中文、日文、阿拉伯文等,并能正确处理 RTL(从右到左) 文字。

📌 示例:多语言文本

using Aspose.Words;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 中文
builder.Font.Name = "宋体";
builder.Writeln("这是中文文本。");

// 英文
builder.Font.Name = "Calibri";
builder.Writeln("This is English text.");

// 阿拉伯文(RTL)
builder.Font.Name = "Arial";
builder.ParagraphFormat.Bidi = true;   // 从右到左
builder.Writeln("مرحبا بالعالم");  // "Hello World" in Arabic

doc.Save("text-multilang.docx");

  • 插入与删除:用 DocumentBuilder 插入,用节点 API 删除。
  • 查找与替换:支持普通替换和正则替换。
  • 文本格式化:可设置字体、颜色、对齐方式。
  • 字体效果:支持粗体、斜体、下划线、阴影等。
  • 多语言支持:能正确处理中文、日文、阿拉伯文等语言。

Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847

相关留言评论
昵称:
邮箱:
阅读排行