文档星空最火知名网站>>Spire.Doc系列教程>>Spire.Doc系列教程(18):在word文档中查找和替换并删除特殊符号
Spire.Doc系列教程(18):在word文档中查找和替换并删除特殊符号
更多资源查看:Spire.XLS工作表教程 | Spire.Doc系列教程 | Spire.PDF系列教程
Spire.Doc for .NET是一个专业的Word
.NET库,设计用于帮助开发人员高效地开发创建、阅读、编写、转换和打印任何来自.NET( C#, VB.NET,
ASP.NET)平台的Word文档文件的功能。以下示例将详细讲述如何使用Spire.Doc在Word文档中查找和替换并删除特殊符号。
C# Word 查找和替换功能
Spire.Doc 为开发者提供了查找和替换功能的方法,我们可以通过document.FindString()方法查找文档中某一个特定词汇并对它进行高亮替换,也可以通过document.FindAllString()方法查找文本中所有地该词汇对将找到的词汇使用Document.Replace()方法进行替换更改。该文将详细介绍如何使用C#来实现word查找,替换和高亮显示功能。
//新建一个word文档对象并加载sample文档
Document document = new Document();
document.LoadFromFile("Test.docx", FileFormat.Docx2010);
//查找一个特定字符串 ”Spire.Doc”
TextSelection selection = document.FindString("Spire.Doc", false, true);
TextRange range = selection.GetAsOneRange();
//替换字符串
range.Text = "Replaced Text";
//设置高亮颜色
range.CharacterFormat.HighlightColor = Color.Yellow;
//查找文档中所有字符串 ”Microsoft”
TextSelection[] text = document.FindAllString("Microsoft", false, true);
//设置高亮颜色
foreach (TextSelection seletion in text)
{
seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green;
}
//使用 ”MS” 替换所有 ”Microsoft”
document.Replace("Microsoft", "MS", false, true);
//保存文档
document.SaveToFile("Result.docx", FileFormat.Docx2010);效果图如下:

C# Word 中添加和删除特殊符号
Word允许通过插入符号操作来向文档中添加一些键盘上没有的特殊符号,本文将介绍如何使用Spire.Doc来进行同样的操作。
//实例化一个Document对象
Document doc = new Document();
//向文档中添加一个Section对象
Section sec = doc.AddSection();
//在这个section上添加一个段落
Paragraph p = sec.AddParagraph();
p.AppendText("这是一个打勾的复选框:");
//在段落之后追加一个打勾的复选框,这个符号的十六进制是"\u0052",
//也可以用十进制(char)82).ToString()来表示它。
//TextRange tr=p.AppendText("\u0052");
TextRange tr= p.AppendText(((char)82).ToString());
//设置字体,可以在word中查看对应的符号是什么字体,这里打勾的复选框是Wingdings2字体
tr.CharacterFormat.FontName = "Wingdings 2";
//添加一个新的段落,并添加一个邮件图标
Paragraph p1 = sec.AddParagraph();
p1.AppendText("这是一个邮件图标:");
//TextRange tr1 = p1.AppendText("\u002A");
TextRange tr1 = p1.AppendText(((char)42).ToString());
tr1.CharacterFormat.FontName = "Wingdings";
//添加一个新的段落,并添加一个笑脸符号
Paragraph p2 = sec.AddParagraph();
p2.AppendText("这是一个笑脸符号:");
//TextRange tr2 = p2.AppendText("\u004A");
TextRange tr2 = p2.AppendText(((char)74).ToString());
tr2.CharacterFormat.FontName = "Wingdings";
//保存文档
doc.SaveToFile("添加特殊符号.docx");效果图如下:

删除特殊符号
//实例化一个Document对象
Document doc = new Document();
//加载文档
doc.LoadFromFile("特殊符号.docx");
//用FindString方法找到要删除的邮件图标
TextRange tr = doc.FindString("\u002A", true, true).GetAsOneRange();
//定位到这个TextRange所在的段落然后删除这个TextRange
Paragraph p = tr.OwnerParagraph;
p.ChildObjects.Remove(tr);
//保存文档
doc.SaveToFile("test.docx", FileFormat.Docx2013);效果图如下:

如果你有任何问题或意见,可在下方评论区留言,点击资源列表查看更多教程资源~

QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线