Open a Word Processing Document from a filename using Open XML SDK 2.0

Description:

In this blog you will see how to open a word processing document from a filename and add a text to the main document part using Open XML SDK 2.0.

Assembly:

DocumentFormat.OpenXml.dll

Namesapces:

using DocumentFormat.OpenXml;

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Wordprocessing;

Code:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DocumentFormat.OpenXml;

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Wordprocessing;

 

namespace OpenXMLConsole

{

    class Program

    {

        static void Main(string[] args)

        {        

            string path = @"E:\OpenXMLTest.docx";

            //// Creates the new instance of the WordprocessingDocument class from the specified file

            //// WordprocessingDocument.Open(String, Boolean) method

            //// Parameters:

            //// string path - path is a string which contains the path of the document

            //// bool isEditable

            using (WordprocessingDocument doc = WordprocessingDocument.Open(path,true))

            {

                //// Defines the MainDocumentPart

                MainDocumentPart mainPart = doc.MainDocumentPart;

                mainPart.Document = new Document(

                    new Body(

                        new Paragraph(

                            new Run(

                                new Text("HI!!!!!!")))));

            }

        }

    }

}