我有一个MS Word 2003文档,其中包含/FirstName/, /LastName/
等占位符...我使用Microsoft Office 12 Library来读取文件,并使用通配符Find.Text = "/[A-Z]*/"
进行搜索。它工作正常,Find.Execute
确实找到了占位符。但因为它只返回布尔值,所以我不知道如何获取占位符本身。
您能告诉我如何获取通配符
搜索的文本答案 0 :(得分:1)
我建议使用单词书签而不是占位符,因为文本没有显示给用户,你可以使用这个来自动插入文本,因为你可以获得特定书签的范围:
protected void insertTextAt(string bookmarkName, string text,
bool useDefaults = true, string fontName = "Arial",
int fontSize = 11, int bold = 0,bool newLine = true)
{
try
{
Object oBookMarkName = bookmarkName;
WordInterop.Range wRng =
this.wDoc.Bookmarks.get_Item(ref oBookMarkName).Range;
wRng.Text = text;
if (!useDefaults)
{
wRng.Font.Bold = bold;
wRng.Font.Name = fontName;
wRng.Font.Size = fontSize;
}
if (newLine)
{
wRng.Text += "\r\n";
}
wRng.Font.Bold = 0;
}
catch (Exception e)
{
String exceptionString = String.Format("Bookmark {0} could not"
+" be found in template {1}",bookmarkName,this.template);
throw new Exception(exceptionString,e);
}
}
答案 1 :(得分:0)
这是我的代码,为了您的兴趣。
首先,这是letter.doc
个文件
亲爱的/ FirstName / / MiddleName / / LastName /:
欢迎来到我们的计划。我们致力于为您提供最高价 质量的客户服务......
我还有Dictionary<string, string> Data
存储每个占位符的键/值
...
"/FirstName/" : "read from database"
"/MiddleName/" : "read from database"
"/LastName/" : "read from database"
...
我有一个读取.doc文件并替换占位符的方法:
oWordApp = new MSWord.ApplicationClass();
doc = oWordApp.Documents.Open(ref fileName,
ref missing, ref readOnly,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible,
ref missing, ref missing, ref missing);
doc.Activate();
doc.Select();
oWordApp.Selection.Find.ClearFormatting();
oWordApp.Selection.Find.MatchWildcards = true;
oWordApp.Selection.Find.Wrap = MSWord.WdFindWrap.wdFindContinue;
oWordApp.Selection.Find.Text = "/[A-Z]*/";
bool isFound = true;
while(isFound == true) {
isFound = oWordApp.Selection.Find.Execute(ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
if( isFound == true ) {
//use the database to do the replacing
//how to get the placeholder itself, such as "/FirstName/", "/LastName/",...
}
}