[英]Creating word add in with OpenXML to insert new MergeField
我是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時它什么也沒做。感謝您的幫助。
添加一個try / catch,您可能會發現它無法打開文件,因為該文件當前已打開以進行編輯。
OpenXML SDK是一個用於在不通過Office界面的情況下寫入Office文件的庫。 但是,您在嘗試使用Office界面的同時嘗試這樣做,因此您實際上在嘗試同時采用兩種方法。 除非您首先關閉文檔,否則這將無法正常工作。
但是您可能要使用VSTO。 在VSTO中,每個文檔都有一個Fields集合,可用於添加字段。
Fields.Add(Range, Type, Text, PreserveFormatting)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.