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

如何从列表中的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文档?

解决方法

安装 OpenXML SDK后,您可以参考DocumentFormat.OpenXml程序集:Add Reference – >装配 – >
扩展 – > 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")))));
            }
        }
    }
}

此外,您可以使用生产力工具(相同的链接)从文档生成代码.它可以帮助了解如何使用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);
                }
            }
        }
    }
}

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

这是关于COM互操作:How do I properly clean up Excel interop objects?的非常有用的东西

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...