[英]Creating word add in with OpenXML
I'm new to VSTO and OpenXML and I would like to develop some Word add-in. 我是VSTO和OpenXML的新手,我想开发一些Word加载项。 This add-in should use OpenXML, so is it possible to edit opened document?
此加载项应使用OpenXML,因此可以编辑打开的文档吗? For example I have opened Word document and I would like to replace some text using OpenXML on button click.
例如,我已经打开Word文档,并且想在单击按钮时使用OpenXML替换一些文本。
So I have this code. 所以我有这段代码。
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);
And i found this to add text to Word using OpenXML How to: Open and add text to a word processing document (Open XML SDK) 我发现这可以使用OpenXML将文本添加到Word中如何:打开并将文本添加到文字处理文档中(Open XML SDK)
But i can't figure out how to make them work together. 但是我不知道如何使它们一起工作。
Can anyone help me with this, Thanks 有人可以帮我吗,谢谢
You can do something like that; 你可以做类似的事情。
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);
}
}
}
Please read this post for more details. 请阅读此帖子以获取更多详细信息。
https://msdn.microsoft.com/en-us/library/office/bb508261.aspx https://msdn.microsoft.com/zh-CN/library/office/bb508261.aspx
This is how i solved it: 这就是我解决的方法:
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.