微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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?的非常有用的东西

原文地址:https://www.jb51.cc/csharp/96941.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐