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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19656626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:33:02  来源:igfitidea点击:

How do I create the .docx document with Microsoft.Office.Interop.Word?

c#.net-4.0ms-worddocx

提问by novicegis

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

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

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

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?

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

回答by Evgeny Timoshenko

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

安装OpenXML SDK 后,您将能够引用DocumentFormat.OpenXml程序集: Add Reference-> Assemblies-> Extensions-> DocumentFormat.OpenXml。您还需要参考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.

您也可以使用生产力工具(相同的链接)从文档生成代码。它可以帮助理解如何使用 SDK API。

You can do the same with Interop:

您可以使用 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.

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



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

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

回答by Amol Khandagale

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

如果您不想使用 Microsoft 互操作办公室,那么

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

参考 C-尖角

回答by Salih KARAHAN

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.

如果您不知道如何访问 office 2016 互操作对象,请访问链接 ( https://social.msdn.microsoft.com/Forums/vstudio/en-US/55fe7d16-998b-4c43-9746-45ff35310158/office-2016 -interop-assemblies?forum=exceldev) 可以为您提供帮助。

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

在此之后,您可以尝试@Evgeny Timoshenko 的示例。

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);
            }
        }
    }
}