我正在使用visual studio express 2015和word interop 14.0。
我需要在C#中使用Word Interop在word文档的最后一页的页脚中添加If条件。我搜索了代码以及其他论坛,但无法在C#中使用它。请帮忙。
我的问题是如何在页脚部分添加IF条件,以便它只在最后一页中进行dipslays。
条件是:
if page = numpages then "Last Page Footer Text" else "Other page footer text"
我使用了以下代码,但它显示在所有页面中,并且if条件也显示在页脚中。
object fieldPages = WdFieldType.wdFieldPage;
object fieldNumPages = WdFieldType.wdFieldNumPages;
object fieldMerge = WdFieldType.wdFieldMergeField;
object fieldAuthor = WdFieldType.wdFieldAuthor;
object fieldIF = WdFieldType.wdFieldIf;
object collapseDirection = WdCollapseDirection.wdCollapseStart;
object txt = string.Empty;
var field = Rng.Fields.Add(Rng, ref fieldAuthor, ref txt, true);
Rng.InsertAfter("\"");
Rng.InsertBefore("\"");
Rng.Collapse(ref collapseDirection);
oDoc.Fields.Add(Rng, ref fieldNumPages, ref txt, true);
Rng.InsertBefore(" = ");
Rng.Collapse(ref collapseDirection);
oDoc.Fields.Add(Rng, ref fieldPages, ref txt, true);
Rng.InsertBefore(" IF ");
Rng.Collapse(ref collapseDirection);
oWord.ActiveWindow.ActivePane.View.ShowFieldCodes = true;
field.Update();
答案 0 :(得分:0)
使用对象模型创建嵌套字段很复杂 - 它没有任何内容可以促进这个过程。尝试通过创建最里面的字段来模仿UI,选择它们,然后插入字段括号有点棘手,必须编写每个组合的代码。
使用对象模型,为字段嵌套在其中的最外层字段写入占位符更有意义。然后Word的Range.Find功能可以拾取占位符并在其位置插入域代码。
以下是一些示例代码,用于创建您描述的条件页脚文本:
//Returns the changed field code
private string GenerateNestedField(Word.Field fldOuter,
string sPlaceholder)
{
Word.Range rngFld = fldOuter.Code;
Word.Document doc = (Word.Document) fldOuter.Parent;
bool bFound;
string sFieldCode;
//Get the field code from the placeholder by removing the { }
sFieldCode = sPlaceholder.Substring(1, sPlaceholder.Length - 2); //Mid(sPlaceholder, 2, Len(sPlaceholder) - 2)
rngFld.TextRetrievalMode.IncludeFieldCodes = true;
bFound = rngFld.Find.Execute(sPlaceholder);
if (bFound) doc.Fields.Add(rngFld, Word.WdFieldType.wdFieldEmpty, sFieldCode, false);
return fldOuter.Code.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
getWordInstance(); //Object defined as a class member for Word.Application
Word.Document doc = wdApp.ActiveDocument;
Word.View vw = doc.ActiveWindow.View;
Word.Range rngTarget = null;
Word.Field fldIf = null;
string sIfField, sFieldCode;
string sQ = '"'.ToString();
bool bViewFldCodes = false;
sIfField = "IF {Page} = {NumPages} " + sQ + "Last" + sQ + " " + sQ + "Other" + sQ;
rngTarget = doc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
bViewFldCodes = vw.ShowFieldCodes;
//Finding text in a field codes requires field codes to be shown
if(!bViewFldCodes) vw.ShowFieldCodes = true;
//Create the nested field: { IF {Pages} = {NumPages} "Last" "Other" }
fldIf = doc.Fields.Add(rngTarget, Word.WdFieldType.wdFieldEmpty, sIfField, false);
sFieldCode = GenerateNestedField(fldIf, "{Page}");
sFieldCode = GenerateNestedField(fldIf, "{NumPages}");
rngTarget.Fields.Update();
vw.ShowFieldCodes = bViewFldCodes;
}