11

How do I create the .docx document with Microsoft.Office.Interop.Word from List? or the best way is to add docx.dll?

http://www.c-sharpcorner.com/UploadFile/scottlysle/using-the-docx-dll-to-programmatically-create-word-documents/

Update. May be my first question is a litle incorrect. What is the difference between Microsoft.Office.Interop.Word and DocX.dll? Do I need Microsft Word for creating and opening .docx document in both cases?

novicegis
  • 519
  • 3
  • 5
  • 13
  • 1
    Interop.Word requires Office to be installed on the machine. DocX does not, it hacks the OpenXML content of a .docx file directly. The usual choice is the Open XML SDK. Long-term support for this library would normally be something to fret about. Review the Issues list for known problems. – Hans Passant Oct 29 '13 at 13:13

3 Answers3

20

upd: It seems like openxml sdk is now being installed via nuget, take a look at their github repo https://github.com/OfficeDev/Open-XML-SDK

After installing OpenXML SDK you will able to reference DocumentFormat.OpenXml assembly: Add Reference -> Assemblies -> Extensions -> DocumentFormat.OpenXml. Also you will need to reference WindowsBase.

Than you will be able to generate document, for example, like this:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace MyNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var document = WordprocessingDocument.Create(
                "test.docx", WordprocessingDocumentType.Document))
            {
                document.AddMainDocumentPart();
                document.MainDocumentPart.Document = new Document(
                    new Body(new Paragraph(new Run(new Text("some text")))));
            }
        }
    }
}

Also you can use Productivity Tool (the same link) to generate code from document. It can help to understand how work with SDK API.

You can do the same with Interop:

using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;

namespace Interop1
{
    class Program
    {
        static void Main(string[] args)
        {
            Application application = null;
            try
            {
                application = new Application();
                var document = application.Documents.Add();
                var paragraph = document.Paragraphs.Add();
                paragraph.Range.Text = "some text";

                string filename = GetFullName();
                application.ActiveDocument.SaveAs(filename, WdSaveFormat.wdFormatDocument);
                document.Close();
            
            }
            finally
            {
                if (application != null)
                {
                    application.Quit();
                    Marshal.FinalReleaseComObject(application);
                }
            }
        }
    }
}

But in this case you should reference COM type library Microsoft. Word Object Library.


Here are very useful things about COM interop: How do I properly clean up Excel interop objects?

Evgeny Timoshenko
  • 3,119
  • 5
  • 33
  • 53
  • 4
    If you wanna go the interop way, you should also Quit the application object and release the com object. Otherwise you will end up with huge memory leaks. This is why http://alemiralles.blogspot.com.ar/2012/11/how-to-create-word-documents-from.html – Ale Miralles Nov 04 '13 at 15:34
  • That link is bad. – KFP Aug 31 '16 at 15:04
0

If you don't want to use Microsoft interop office then

I really liked this

//Add reference DocX.dll

using Novacode;

  // reference to the working document.
        static DocX gDocument;

 public void CreateWithOpenDoc(string _fileName, string _saveAs, int _LeadNo)
        {
            if (File.Exists(_fileName))
            {

                gDocument = DocX.Load(_fileName);



                //--------------------- Make changes -------------------------------

                // Strong-Type
                Dictionary<string, string> changesList = GetChangesList(_LeadNo, dt.Rows[0]);

                foreach (KeyValuePair<string, string> keyValue in changesList)
                {
                    gDocument.ReplaceText(keyValue.Key.ToString().Trim(), keyValue.Value.ToString().Trim(), false);
                }

                //------------------------- End of make changes ---------------------


                gDocument.SaveAs(_saveAs);

            }

        }

take reference C-sharp corner

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Amol Khandagale
  • 111
  • 2
  • 5
  • 1
    FYI ... I have used DocX (Xceed.Words) for months. But recently after updating to the latest version it stopped working because it now requires a key, and the cost to purchase DocX is over $500. So I'll be switching over to Microsoft.Interop – HeadlyvonNoggin Nov 21 '19 at 16:17
0

If you don't know how to access office 2016 interop objects, the link (https://social.msdn.microsoft.com/Forums/vstudio/en-US/55fe7d16-998b-4c43-9746-45ff35310158/office-2016-interop-assemblies?forum=exceldev) can help to you.

After this, You can try @Evgeny Timoshenko's example.

class Program
{
    static void Main(string[] args)
    {
        Application application = null;
        try
        {
            application = new Application();
            var document = application.Documents.Add();
            var paragraph = document.Paragraphs.Add();
            paragraph.Range.Text = "some text";

            string filename = GetFullName();
            application.ActiveDocument.SaveAs(filename, WdSaveFormat.wdFormatDocument);
            document.Close();

        }
        finally
        {
            if (application != null)
            {
                application.Quit();
                Marshal.FinalReleaseComObject(application);
            }
        }
    }
}
Salih KARAHAN
  • 299
  • 1
  • 4
  • 18