Как сохранить документ в DOCX формат на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите или создайте документ.
  3. Сохраните в формате DOCX.
  1. Сохранить в файл:
    
                // The file format will be detected automatically from the file extension: ".docx".
                dc.Save(@"d:\Book.docx");
    

    Чтобы не полагаться на расширение файла и гарантировать, что содержимое файла действительно DOCX, Вы можете указать DocxSaveOptions в качестве второго параметра.

    
    dc.Save(@"d:\Book.docx", new DocxSaveOptions());
    

    В DocxSaveOptions Вы также можете установить различные параметры, влияющие на процесс сохранения.

    
                dc.Save(@"d:\Book.docx", new DocxSaveOptions()
                {
                    Format = DocxFormat.Docm,
                    Password = "123"
                });
    
  2. Сохранить в поток:
                // Let's save our document to a MemoryStream.
                using (MemoryStream ms = new MemoryStream())
                {                
                    dc.Save(ms, new DocxSaveOptions());
                }
    

Полный код

using System.IO;
using SautinSoft.Document;

namespace Example
{
    class Program
    {
       
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            SaveToDocxFile();
            SaveToDocxStream();
        }

        /// <summary>
        /// Creates a new document and saves it as DOCX file.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-docx-net-csharp-vb.php
        /// </remarks>
        static void SaveToDocxFile()
        {
            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();
            dc.Content.End.Insert("Hey from File!");

            string filePath = @"Result-file.docx";

            dc.Save(filePath, new DocxSaveOptions());

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });

        }

        /// <summary>
        /// Creates a new document and saves it as DOCX using MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-docx-net-csharp-vb.php
        /// </remarks>
        static void SaveToDocxStream()
        {
            // There variables are necessary only for demonstration purposes.
            byte[] fileData = null;
            string filePath = @"Result-stream.docx";

            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();
            dc.Content.End.Insert("Hey from MemoryStream!");

            // Let's save our document to a MemoryStream.
            using (MemoryStream ms = new MemoryStream())
            {
                dc.Save(ms, new DocxSaveOptions());
                fileData = ms.ToArray();
            }
            File.WriteAllBytes(filePath, fileData);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        SaveToDocxFile()
        SaveToDocxStream()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Creates a new document and saves it as DOCX file.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-docx-net-csharp-vb.php
    ''' </remarks>
    Sub SaveToDocxFile()
        ' Assume we already have a document 'dc'.
        Dim dc As New DocumentCore()
        dc.Content.End.Insert("Hey from File!")

        Dim filePath As String = "Result-file.docx"

        dc.Save(filePath, New DocxSaveOptions())

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})

    End Sub

    ''' <summary>
    ''' Creates a new document and saves it as DOCX using MemoryStream.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-docx-net-csharp-vb.php
    ''' </remarks>
    Sub SaveToDocxStream()
        ' There variables are necessary only for demonstration purposes.
        Dim fileData() As Byte = Nothing
        Dim filePath As String = "Result-stream.docx"

        ' Assume we already have a document 'dc'.
        Dim dc As New DocumentCore()
        dc.Content.End.Insert("Hey from MemoryStream!")

        ' Let's save our document to a MemoryStream.
        Using ms As New MemoryStream()
            dc.Save(ms, New DocxSaveOptions())
            fileData = ms.ToArray()
        End Using
        File.WriteAllBytes(filePath, fileData)

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
    End Sub
End Module

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.