[英]Creating word add in with OpenXML
我是VSTO和OpenXML的新手,我想开发一些Word加载项。 此加载项应使用OpenXML,因此可以编辑打开的文档吗? 例如,我已经打开Word文档,并且想在单击按钮时使用OpenXML替换一些文本。
所以我有这段代码。
var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;
Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);
//edit document using OpenXml here
Globals.ThisAddIn.Application.Documents.Open(fileFullName);
我发现这可以使用OpenXML将文本添加到Word中如何:打开并将文本添加到文字处理文档中(Open XML SDK)
但是我不知道如何使它们一起工作。
有人可以帮我吗,谢谢
你可以做类似的事情。
public static void SearchAndReplace(string document)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
请阅读此帖子以获取更多详细信息。
https://msdn.microsoft.com/zh-CN/library/office/bb508261.aspx
这就是我解决的方法:
private void button1_Click(object sender, RibbonControlEventArgs e)
{
var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;
Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);
OpenAndAddTextToWordDocument(fileFullName, "[USER_NAME]");
Globals.ThisAddIn.Application.Documents.Open(fileFullName);
}
public static void 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 new text.
DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));
// Close the handle explicitly.
wordprocessingDocument.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.