Как создать документ .docx с помощью Microsoft.Office.Interop.Word? - программирование
Подтвердить что ты не робот

Как создать документ .docx с помощью Microsoft.Office.Interop.Word?

Как создать документ .docx с Microsoft.Office.Interop.Word из списка? или лучше всего добавить docx.dll?

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

Update. Может быть, мой первый вопрос - это неправильно. В чем разница между Microsoft.Office.Interop.Word и DocX.dll? Нужно ли мне Word Microsft для создания и открытия документа .docx в обоих случаях?

4b9b3361

Ответ 1

После установки OpenXML SDK вы сможете ссылаться на сборку DocumentFormat.OpenXml: Add ReferenceAssembliesExtensionsDocumentFormat.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")))));
            }
        }
    }
}

Также вы можете использовать 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);
                }
            }
        }
    }
}

Но в этом случае вам следует обратиться к библиотеке COM-типа Microsoft. Библиотека объектов Word.


Вот очень полезные вещи о COM-взаимодействии: Как правильно очистить объекты взаимодействия Excel?

Ответ 2

Если вы не хотите использовать офис Microsoft interop, то

Мне это очень понравилось

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

            }

        }

взять ссылку  C-sharp corner

Ответ 3

Если вы не знаете, как получить доступ к объектам interop office 2016, ссылка (https://social.msdn.microsoft.com/Forums/vstudio/en-US/55fe7d16-998b-4c43-9746-45ff35310158/office-2016-interop-assemblies?forum=exceldev) может вам помочь.

После этого вы можете попробовать пример Евгения Тимошенко.

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