Как клонировать элемент в документе DOCX с помощью C# и .NET


Любой экземпляр элемента может быть вставлен в ядро документа только один раз. Чтобы вставить элемент в какую-либо другую часть того же документа, он должен быть клонирован, и клон должен быть вставлен.

Полный код

using System;
using SautinSoft.Document;
using System.IO;
using System.Linq;
using System.Text;

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

            CloningElement();
        }

        /// <summary>
        /// How to clone an element in DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/cloning-element-net-csharp-vb.php
        /// </remarks>
        static void CloningElement()
        {
            string filePath = @"..\..\..\Parsing.docx";
            string cloningFile = "Cloning.docx";
            DocumentCore dc = DocumentCore.Load(filePath);

            // Clone section.
            dc.Sections.Add(dc.Sections[0].Clone(true));

            // Clone paragraphs.
            foreach (Block item in dc.Sections[0].Blocks)
                dc.Sections.Last().Blocks.Add(item.Clone(true));

            // Save the result.
            dc.Save(cloningFile);

            // Show the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(cloningFile) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports SautinSoft.Document
Imports System.IO
Imports System.Linq
Imports System.Text

Module Sample
    Sub Main()
        CloningElement()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' How to clone an element in DOCX document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/cloning-element-net-csharp-vb.php
    ''' </remarks>
    Sub CloningElement()
        Dim filePath As String = "..\..\..\Parsing.docx"
        Dim cloningFile As String = "Cloning.docx"
        Dim dc As DocumentCore = DocumentCore.Load(filePath)

        ' Clone section.
        dc.Sections.Add(dc.Sections(0).Clone(True))

        ' Clone paragraphs.
        For Each item As Block In dc.Sections(0).Blocks
            dc.Sections.Last().Blocks.Add(item.Clone(True))
        Next item

        ' Save the result.
        dc.Save(cloningFile)

        ' Show the results.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(cloningFile) With {.UseShellExecute = True})
    End Sub
End Module

Download


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



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

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