1
votes

I'm new to VSTO and OpenXML and I would like to develop some Word add-in. This add-in should use OpenXML, so is it possible to edit opened document? For example I have opened Word document and I would like to replace some text using OpenXML on button click.

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)

But i can't figure out how to make them work together.

Can anyone help me with this, Thanks

2

2 Answers

1
votes

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();
        }

    }
0
votes

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