【发布时间】:2017-12-11 07:55:53
【问题描述】:
我是 VSTO 和 OpenXML 的新手,我想开发一个 Word 插件。这个加载项应该使用 OpenXML,加载项应该向文档添加一个 MergeField,我实际上可以使用 ConsoleApp 添加 MergeField,但我想将 Word 加载项中的 MergeField 插入到当前打开的文档中。
所以我在 ButtonClick 中有这段代码
// take current file location
var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;
Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);
// function to insert new field here
OpenAndAddTextToWordDocument(fileFullName, "username");
Globals.ThisAddIn.Application.Documents.Open(fileFullName);
我创建了应该添加新 MergeField 的函数:
public static DocumentFormat.OpenXml.Wordprocessing.Paragraph OpenAndAddTextToWordDocument(string filepath, string txt)
{
// Open a WordprocessingDocument for editing using the filepath.
WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(filepath, true);
// Assign a reference to the existing document body.
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
// add text
string instructionText = String.Format(" MERGEFIELD {0} \\* MERGEFORMAT", txt);
SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Text text1 = new Text();
text1.Text = String.Format("«{0}»", txt);
run1.Append(runProperties1);
run1.Append(text1);
simpleField1.Append(run1);
DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
paragraph.Append(new OpenXmlElement[] { simpleField1 });
return paragraph;
// Close the handle explicitly.
wordprocessingDocument.Close();
但是这里有些东西不起作用,当我使用 add 时,它什么也没做 感谢您的帮助。
【问题讨论】:
标签: c# ms-word vsto openxml word-addins