我有一个模板 word 文档,我正在使用一个函数将特定文本替换为我想要的文本。它适用于整个文档(主体和标题),但最后一页的标题除外,它是横向页面。
void FindAndReplace2(Microsoft.Office.Interop.Word.Document document, string placeHolder, string newText)
{
object missingObject = null;
object item = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
object whichItem = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
object forward = true;
object matchAllWord = true;
object matchCase = false;
object originalText = placeHolder;
object replaceText = newText;
document.GoTo(ref item, ref whichItem, ref missingObject, ref missingObject);
foreach (Microsoft.Office.Interop.Word.Range rng in document.StoryRanges)
{
rng.Find.Execute(ref originalText, ref matchCase,
ref matchAllWord, ref missingObject, ref missingObject, ref missingObject, ref forward,
ref missingObject, ref missingObject, ref replaceText, ref replaceAll, ref missingObject,
ref missingObject, ref missingObject, ref missingObject);
}
}
我不确定为什么这个功能可以在除横向页面之外的所有内容上工作。我不知道如何从这里开始。
主要示例文件
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
// Start Word and create a new document.
Word.Application oWord;
Word.Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
//Template file
object oTemplate = @"FILEPATH";
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
string SiteName="J8865";
FindAndReplace2(oDoc, "Sample", SiteName);
注意:这个文件只是我的主文件的摘录。