Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847
在 Aspose.Words for .NET 中,文本操作 是最常见的功能之一。无论是插入与删除、查找替换,还是格式化与多语言处理,Aspose.Words 都提供了灵活的 API。
使用 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");
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");
支持 正则表达式 (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");
可以为插入的文本应用字体、颜色、对齐方式等格式化设置。
📌 示例:加粗、设置颜色和对齐
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");
可以控制字体大小、样式(粗体/斜体/下划线)、文字阴影等效果。
📌 示例:字体设置
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");
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