我有一个在word文档中查找和替换文本占位符的函数。它可以很好地处理短文本字符串。但是,当尝试替换为更大的文本字符串时,不执行任何操作。
DocReplaceField(ref Word.Document objDoc, string Field, string Value)
{
object missing = System.Reflection.Missing.Value;
Word.Range range = objDoc.Content;
object findtext = Field;
object f = false;
object findreplacement = Value;
object findforward = false;
object findformat = true;
object findwrap = WdFindWrap.wdFindContinue;
object findmatchcase = false;
object findmatchwholeword = false;
object findmatchwildcards = false;
object findmatchsoundslike = false;
object findmatchallwordforms = false;
object findreplace = WdReplace.wdReplaceAll;
range.Find.Execute(
findtext,
findmatchcase,
findmatchwholeword,
findmatchwildcards,
findmatchsoundslike,
findmatchallwordforms,
findforward,
findwrap,
findformat,
findreplacement,
findreplace,
missing,
missing,
missing,
missing);
}如果我尝试将"placeholder“替换为"Something”,那么如何将"placeholder“替换为
"Nullam non lorem sapien,et imperdiet sapien. Curabitur vestibulum ut eu enim bibendum .整数velit non elit molestie non ut nisi. Suspendisse potenti. Donec augue,vestibulum a pulvinar id,scelerisque mauris.整数eget ullamcorper velit. Sed at purus sit amet felis at non neque. Praesent laoreet mauris sem venenatis pellentesque.“
例如
更新:
问题似乎是word的查找和替换不能替换超过255个字符。搜索与占位符匹配,但无法实际替换文本。有没有人有这样的例子:调用find来定位占位符,然后手动选择文本并插入新文本。而不是使用查找和替换这个词。
发布于 2013-01-08 21:31:26
替换文本非常简单:一旦找到文本,range对象将包含文档中找到的部分。您需要先删除找到的文本,然后插入新的文本:
range.Find.Execute(findtext, findmatchcase, findmatchwholeword,
findmatchwildcards, findmatchsoundslike, findmatchallwordforms, findforward,
findwrap, findformat, findreplacement, findreplace, missing,
missing, missing, missing);
range.Delete();
range.Text = "This is the new content.";发布于 2015-11-09 20:45:43
我所做的是将替换字符串拆分成更小的片段,并在除最后一个字符串之外的每个字符串的末尾添加占位符,然后像字符串片段一样多次重复replace命令。它也适用于较小的字符串,因此您不必使用不同的方法:
string acierto; // where acierto is my placeholder
string[] cadenas;
cadenas = BSV.Funciones.ParteCadenas(valor, 170); // function to split a string into 170 character pieces
for (int xx = 0; xx < cadenas.Length; xx++)
{
if (xx < cadenas.Length - 1) cadenas[xx] += acierto;
parrafo.Range.Find.Execute(acierto, nulo, nulo, nulo, nulo, nulo, nulo, nulo, nulo, cadenas[xx], WdReplace.wdReplaceAll, nulo, nulo, nulo, nulo);
}发布于 2013-01-08 20:54:57
您可以尝试使用Word书签而不是查找和替换吗?
一个示例狙击手-
object oBookMark = "MyBookmark";
oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";https://stackoverflow.com/questions/14215308
复制相似问题