如何使用Microsoft.Office.Interop.Word创建.docx文档?

nov*_*gis 10 c# ms-word docx .net-4.0

如何使用List中的Microsoft.Office.Interop.Word创建.docx文档?或者最好的方法是添加docx.dll?

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

更新.可能是我的第一个问题是痘痘不正确.Microsoft.Office.Interop.Word和DocX.dll有什么区别?在这两种情况下,我是否需要使用Microsft Word来创建和打开.docx文档?

Evg*_*nko 18

安装OpenXML SDK后,您将能够引用DocumentFormat.OpenXml程序集: Add Reference- > Assemblies- > Extensions- > DocumentFormat.OpenXml.您还需要参考WindowsBase.

比你能够生成文档,例如,像这样:

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")))));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用Productivity Tool(相同的链接)从文档生成代码.它有助于了解如何使用SDK API.

您可以使用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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,您应该引用COM类型库Microsoft.Word对象库.


以下是关于COM互操作的非常有用的东西:如何正确清理Excel互操作对象?

  • 如果您想采用互操作方式,还应该退出应用程序对象并释放com对象.否则你最终会出现巨大的内存泄漏.这就是为什么http://alemiralles.blogspot.com.ar/2012/11/how-to-create-word-documents-from.html (3认同)