我是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时,它不会做任何事情,谢谢你的帮助。
发布于 2017-12-12 05:03:46
添加try/catch后,您可能会发现它无法打开该文件,因为该文件当前处于打开状态以供编辑。
Office是一个用于写入OpenXML文件的库,无需通过Office的接口。但是您试图在使用Office接口的同时做到这一点,因此您实际上是在尝试同时采用两种方法。除非您首先关闭文档,否则这不会起作用。
但是您可能想要使用VSTO。在VSTO中,每个文档都有一个Fields集合,您可以使用它来添加字段。
Fields.Add(Range, Type, Text, PreserveFormatting)https://stackoverflow.com/questions/47748525
复制相似问题