Les longs articles ou rapports de recherche sont souvent rédigés en collaboration par plusieurs personnes. Pour gagner du temps, chaque personne peut travailler sur les parties qui lui sont assignées dans des documents séparés, puis fusionner ces documents en un seul après avoir terminé l'édition. Outre la copie et le collage manuels du contenu d'un document Word à un autre, cet article présente les deux manières suivantes de fusionner des documents Word par programmation à l'aide de Spire.Doc for .NET .

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for.NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Fusionner des documents en insérant le fichier entier

La méthode Document.InsertTextFromFile() fournie par Spire.Doc for .NET permet de fusionner des documents Word en insérant entièrement d'autres documents dans un document. En utilisant cette méthode, le contenu du document inséré commencera à partir d'une nouvelle page. Les étapes détaillées sont les suivantes :

  • Créez une instance de document.
  • Chargez le document Word d'origine à l'aide de la méthode Document.LoadFromFile().
  • Insérez entièrement un autre document Word dans le document d'origine à l'aide de la méthode Document.InsertTextFromFile().
  • Enregistrez le document de résultat à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MergeWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load the original Word document
                document.LoadFromFile("Doc1.docx", FileFormat.Docx);
    
                //Insert another Word document entirely to the original document
                document.InsertTextFromFile("Doc2.docx", FileFormat.Docx);
    
                //Save the result document
                document.SaveToFile("MergedWord.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Merge Word Documents

Fusionner des documents en clonant le contenu

Si vous souhaitez fusionner des documents sans commencer une nouvelle page, vous pouvez cloner le contenu d'autres documents à ajouter à la fin du document d'origine. Les étapes détaillées sont les suivantes :

  • Chargez deux documents Word.
  • Parcourez le deuxième document pour obtenir toutes les sections à l'aide de la propriété Document.Sections, puis parcourez toutes les sections pour obtenir leurs objets enfants à l'aide de la propriété Section.Body.ChildObjects.
  • Obtenez la dernière section du premier document à l'aide de la propriété Document.LastSection, puis ajoutez les objets enfants à la dernière section du premier document à l'aide de la méthode LastSection.Body.ChildObjects.Add().
  • Enregistrez le document de résultat à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MergeWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load two Word documents
                Document doc1 = new Document("Doc1.docx");
                Document doc2 = new Document("Doc2.docx");
    
                //Loop through the second document to get all the sections
                foreach (Section section in doc2.Sections)
                {
    
                    //Loop through the sections of the second document to get their child objects
                    foreach (DocumentObject obj in section.Body.ChildObjects)
                    {
    
                        // Get the last section of the first document
                         Section lastSection = doc1.LastSection;
    
                        //Add all child objects to the last section of the first document
                        lastSection.Body.ChildObjects.Add(obj.Clone());
                    }
                }
    
                // Save the result document
                doc1.SaveToFile("MergeDocuments.docx", FileFormat.Docx);
            }
        }
    } 

C#/VB.NET: Merge Word Documents

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 31 July 2023 07:02

C#/VB.NET: Criar um documento do Word

Instalado via NuGet

PM> Install-Package Spire.Doc

Links Relacionados

Não há dúvida de que o documento do Word é um dos tipos de arquivo de documento mais populares atualmente. Porque o documento do Word é um formato de arquivo ideal para gerar cartas, memorandos, relatórios, trabalhos de conclusão de curso, romances e revistas, etc. Neste artigo, você aprenderá como criar um documento do Word simples do zero em C# e VB.NET usando o Spire.Doc for .NET.

Spire.Doc for .NET fornece a classe Document para representar um modelo de documento do Word, permitindo que os usuários leiam e editem documentos existentes ou criem novos. Um documento do Word deve conter pelo menos uma seção (representada pela classe Section) e cada seção é um contêiner para elementos básicos do Word, como parágrafos, tabelas, cabeçalhos, rodapés e assim por diante. A tabela abaixo lista as classes e métodos importantes envolvidos neste tutorial.

Membro Descrição
classe de documento Representa um modelo de documento do Word.
classe de seção Representa uma seção em um documento do Word.
Classe de parágrafo Representa um parágrafo em uma seção.
Classe ParagraphStyle Define as informações de formatação de fonte que podem ser aplicadas a um parágrafo.
Método Section.AddParagraph() Adiciona um parágrafo a uma seção.
Método Paragraph.AppendText() Acrescenta texto a um parágrafo no final.
Método Paragraph.ApplyStyle() Aplica um estilo a um parágrafo.
Método Document.SaveToFile() Salva o documento em um arquivo do Word com extensão .doc ou .docx. Este método também suporta salvar o documento em PDF, XPS, HTML, PLC, etc.

Instalar o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for .NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Crie um documento simples do Word

A seguir estão as etapas para criar um documento do Word simples que contém vários parágrafos usando o Spire.Doc for .NET.

  • Crie um objeto Documento.
  • Adicione uma seção usando o método Document.AddSection().
  • Defina as margens da página através da propriedade Section.PageSetUp.Margins.
  • Adicione vários parágrafos à seção usando o método Section.AddParagraph().
  • Adicione texto aos parágrafos usando o método Paragraph.AppendText().
  • Crie um objeto ParagraphStyle e aplique-o a um parágrafo específico usando o método Paragraph.ApplyStyle().
  • Salve o documento em um arquivo do Word usando o método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

Solicitar uma licença temporária

Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Установлено через NuGet

PM> Install-Package Spire.Doc

Ссылки по теме

Нет никаких сомнений в том, что документ Word сегодня является одним из самых популярных типов файлов документов. Поскольку документ Word является идеальным форматом файла для создания писем, заметок, отчетов, курсовых работ, романов, журналов и т. д. В этой статье вы узнаете, как создать простой документ Word с нуля на C# и VB.NET с помощью Spire.Doc for .NET.

Spire.Doc for .NET предоставляет класс Document для представления модели документа Word, позволяя пользователям читать и редактировать существующие документы или создавать новые. Документ Word должен содержать по крайней мере один раздел (представленный классом Section), и каждый раздел является контейнером для основных элементов Word, таких как абзацы, таблицы, верхние и нижние колонтитулы и т. д. В таблице ниже перечислены важные классы и методы, задействованные в этом руководстве.

Член Описание
Класс документа Представляет модель документа Word.
Класс раздела Представляет раздел в документе Word.
Класс абзаца Представляет абзац в разделе.
Класс ParagraphStyle Определяет информацию о форматировании шрифта, которую можно применить к абзацу.
Метод Section.AddParagraph() Добавляет абзац в раздел.
Метод Paragraph.AppendText() Добавляет текст к абзацу в конце.
Метод Paragraph.ApplyStyle() Применяет стиль к абзацу.
Метод Document.SaveToFile() Сохраняет документ в файл Word с расширением .doc или .docx. Этот метод также поддерживает сохранение документа в формате PDF, XPS, HTML, PLC и т. д.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Создайте простой документ Word

Ниже приведены шаги по созданию простого документа Word, содержащего несколько абзацев, с помощью Spire.Doc for .NET.

  • Создайте объект документа.
  • Добавьте раздел с помощью метода Document.AddSection().
  • Установите поля страницы через свойство Section.PageSetUp.Margins.
  • Добавьте в раздел несколько абзацев с помощью метода Section.AddParagraph().
  • Добавьте текст в абзацы, используя метод Paragraph.AppendText().
  • Создайте объект ParagraphStyle и примените его к определенному абзацу, используя метод Paragraph.ApplyStyle().
  • Сохраните документ в файл Word, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

Подать заявку на временную лицензию

Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.

Смотрите также

Über NuGet installiert

PM> Install-Package Spire.Doc

verwandte Links

Es besteht kein Zweifel, dass Word-Dokumente heutzutage einer der beliebtesten Dokumentdateitypen sind. Denn Word-Dokument ist ein ideales Dateiformat zum Erstellen von Briefen, Memos, Berichten, Hausarbeiten, Romanen und Zeitschriften usw. In diesem Artikel erfahren Sie, wie Sie ein einfaches Word-Dokument erstellen von Grund auf in C# und VB.NET mithilfe von Spire.Doc for .NET.

Spire.Doc for .NET stellt die Document-Klasse zur Darstellung eines Word-Dokumentmodells bereit, sodass Benutzer vorhandene Dokumente lesen und bearbeiten oder neue erstellen können. Ein Word-Dokument muss mindestens einen Abschnitt enthalten (dargestellt durch die Abschnittsklasse) und jeder Abschnitt ist ein Container für grundlegende Word-Elemente wie Absätze, Tabellen, Kopf- und Fußzeilen usw. In der folgenden Tabelle sind die wichtigen Klassen und Methoden aufgeführt, die in diesem Tutorial verwendet werden.

Mitglied Beschreibung
Dokumentenklasse Stellt ein Word-Dokumentmodell dar.
Abschnittsklasse Stellt einen Abschnitt in einem Word-Dokument dar.
Absatzklasse Stellt einen Absatz in einem Abschnitt dar.
ParagraphStyle-Klasse Definiert die Schriftartformatierungsinformationen, die auf einen Absatz angewendet werden können.
Section.AddParagraph()-Methode Fügt einem Abschnitt einen Absatz hinzu.
Paragraph.AppendText()-Methode Fügt am Ende Text an einen Absatz an.
Paragraph.ApplyStyle()-Methode Wendet einen Stil auf einen Absatz an.
Document.SaveToFile()-Methode Speichert das Dokument in einer Word-Datei mit der Erweiterung .doc oder .docx. Diese Methode unterstützt auch das Speichern des Dokuments in PDF, XPS, HTML, PLC usw.

Installieren Sie Spire.Doc for .NET

Zunächst müssen Sie die im Spire.Doc for .NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.Doc

Erstellen Sie ein einfaches Word-Dokument

Im Folgenden finden Sie die Schritte zum Erstellen eines einfachen Word-Dokuments, das mehrere Absätze enthält, mithilfe von Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Fügen Sie einen Abschnitt mit der Methode Document.AddSection() hinzu.
  • Legen Sie die Seitenränder über die Section.PageSetUp.Margins-Eigenschaft fest.
  • Fügen Sie dem Abschnitt mit der Methode Section.AddParagraph() mehrere Absätze hinzu.
  • Fügen Sie mit der Methode Paragraph.AppendText() Text zu den Absätzen hinzu.
  • Erstellen Sie ein ParagraphStyle-Objekt und wenden Sie es mit der Paragraph.ApplyStyle()-Methode auf einen bestimmten Absatz an.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer Word-Datei.
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Monday, 31 July 2023 06:58

C#/VB.NET: crear un documento de Word

Instalado a través de NuGet

PM> Install-Package Spire.Doc

enlaces relacionados

No hay duda de que el documento de Word es uno de los tipos de archivos de documentos más populares en la actualidad. Porque el documento de Word es un formato de archivo ideal para generar cartas, memorandos, informes, trabajos finales, novelas y revistas, etc. En este artículo, aprenderá cómo crear un documento de Word simple desde cero en C# y VB.NET usando Spire.Doc for .NET.

Spire.Doc for .NET proporciona la clase Document para representar un modelo de documento de Word, lo que permite a los usuarios leer y editar documentos existentes o crear otros nuevos. Un documento de Word debe contener al menos una sección (representada por la clase Sección) y cada sección es un contenedor de elementos básicos de Word como párrafos, tablas, encabezados, pies de página, etc. La siguiente tabla enumera las clases y métodos importantes involucrados en este tutorial.

Miembro Descripción
clase de documento Representa un modelo de documento de Word.
Clase de sección Representa una sección en un documento de Word.
Clase de párrafo Representa un párrafo en una sección.
clase ParagraphStyle Define la información de formato de fuente que se puede aplicar a un párrafo.
Método Section.AddParagraph() Añade un párrafo a una sección.
Método Paragraph.AppendText() Añade texto a un párrafo al final.
Método Paragraph.ApplyStyle() Aplica un estilo a un párrafo.
Método Document.SaveToFile() Guarda el documento en un archivo de Word con una extensión de .doc o .docx. Este método también admite guardar el documento en PDF, XPS, HTML, PLC, etc.

Instalar Spire.Doc for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Doc for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.Doc

Crear un documento de Word simple

Los siguientes son los pasos para crear un documento de Word simple que contenga varios párrafos utilizando Spire.Doc for .NET.

  • Cree un objeto Documento.
  • Agrega una sección usando el método Document.AddSection().
  • Establezca los márgenes de la página a través de la propiedad Section.PageSetUp.Margins.
  • Agrega varios párrafos a la sección usando el método Section.AddParagraph().
  • Agrega texto a los párrafos usando el método Paragraph.AppendText().
  • Cree un objeto ParagraphStyle y aplíquelo a un párrafo específico usando el método Paragraph.ApplyStyle().
  • Guarde el documento en un archivo de Word utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

Solicitar una Licencia Temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

Monday, 31 July 2023 06:57

C#/VB.NET: Word 문서 만들기

NuGet을 통해 설치됨

PM> Install-Package Spire.Doc

관련된 링크들

Word 문서가 오늘날 가장 널리 사용되는 문서 파일 유형 중 하나라는 데는 의심의 여지가 없습니다. Word 문서는 편지, 메모, 보고서, 기말 보고서, 소설 및 잡지 등을 생성하는 데 이상적인 파일 형식이기 때문입니다 간단한 워드 문서 만들기 처음부터 C# 및 VB.NET 사용하여 Spire.Doc for .NET.

Spire.Doc for .NET은 Word 문서 모델을 나타내는 문서 클래스를 제공하여 사용자가 기존 문서를 읽고 편집하거나 새 문서를 만들 수 있도록 합니다. Word 문서는 적어도 하나의 섹션(Section 클래스로 표시됨)을 포함해야 하며 각 섹션은 단락, 표, 머리글, 바닥글 등과 같은 기본 Word 요소의 컨테이너입니다. 아래 표에는 이 자습서와 관련된 중요한 클래스와 메서드가 나열되어 있습니다.

회원 설명
문서 클래스 Word 문서 모델을 나타냅니다.
섹션 클래스 Word 문서의 섹션을 나타냅니다.
단락 클래스 섹션의 단락을 나타냅니다.
ParagraphStyle 클래스 단락에 적용할 수 있는 글꼴 서식 정보를 정의합니다.
Section.AddParagraph() 메서드 섹션에 단락을 추가합니다.
Paragraph.AppendText() 메서드 끝에 있는 단락에 텍스트를 추가합니다.
Paragraph.ApplyStyle() 메서드 단락에 스타일을 적용합니다.
Document.SaveToFile() 메서드 문서를 확장명이 .doc 또는 .docx인 Word 파일로 저장합니다. 이 방법은 문서를 PDF, XPS, HTML, PLC 등으로 저장하는 것도 지원합니다.

Spire.Doc for .NET 설치

먼저 Spire.Doc for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 다음에서 다운로드할 수 있습니다 이 링크 또는 NuGet을 통해 설치됩니다.

PM> Install-Package Spire.Doc

간단한 Word 문서 만들기

다음은 Spire.Doc for .NET을 사용하여 여러 단락이 포함된 간단한 Word 문서를 만드는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.AddSection() 메서드를 사용하여 섹션을 추가합니다.
  • Section.PageSetUp.Margins 속성을 통해 페이지 여백을 설정합니다.
  • Section.AddParagraph() 메서드를 사용하여 섹션에 여러 단락을 추가합니다.
  • Paragraph.AppendText() 메서드를 사용하여 단락에 텍스트를 추가합니다.
  • ParagraphStyle 객체를 만들고 Paragraph.ApplyStyle() 메서드를 사용하여 특정 단락에 적용합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 Word 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

Installato tramite NuGet

PM> Install-Package Spire.Doc

Link correlati

Non c'è dubbio che il documento Word sia oggi uno dei tipi di file di documento più popolari. Poiché il documento Word è un formato di file ideale per generare lettere, appunti, relazioni, tesine, romanzi e riviste, ecc. In questo articolo imparerai come creare un semplice documento Word da zero in C# e VB.NET utilizzando Spire.Doc for .NET.

Spire.Doc for .NET fornisce la classe Document per rappresentare un modello di documento Word, consentendo agli utenti di leggere e modificare documenti esistenti o crearne di nuovi. Un documento Word deve contenere almeno una sezione (rappresentata dalla classe Section) e ogni sezione è un contenitore per gli elementi base di Word come paragrafi, tabelle, intestazioni, piè di pagina e così via. La tabella seguente elenca le classi e i metodi importanti coinvolti in questo tutorial.

Membro Descrizione
Classe documento Rappresenta un modello di documento di Word.
Classe di sezione Rappresenta una sezione in un documento di Word.
Classe paragrafo Rappresenta un paragrafo in una sezione.
Classe ParagraphStyle Definisce le informazioni sulla formattazione del carattere che possono essere applicate a un paragrafo.
Metodo Section.AddParagraph() Aggiunge un paragrafo a una sezione.
Metodo Paragraph.AppendText() Aggiunge il testo a un paragrafo alla fine.
Metodo Paragraph.ApplyStyle() Applica uno stile a un paragrafo.
Metodo Document.SaveToFile() Salva il documento in un file Word con estensione .doc o .docx. Questo metodo supporta anche il salvataggio del documento in PDF, XPS, HTML, PLC, ecc.

Installa Spire.Doc for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.Doc for .NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.Doc

Crea un semplice documento Word

Di seguito sono riportati i passaggi per creare un semplice documento di Word contenente diversi paragrafi utilizzando Spire.Doc for .NET.

  • Creare un oggetto documento.
  • Aggiungere una sezione utilizzando il metodo Document.AddSection().
  • Impostare i margini della pagina tramite la proprietà Section.PageSetUp.Margins.
  • Aggiungi diversi paragrafi alla sezione usando il metodo Section.AddParagraph().
  • Aggiungi testo ai paragrafi usando il metodo Paragraph.AppendText().
  • Crea un oggetto ParagraphStyle e applicalo a un paragrafo specifico utilizzando il metodo Paragraph.ApplyStyle().
  • Salvare il documento in un file Word utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Monday, 31 July 2023 06:54

C#/VB.NET : créer un document Word

Installé via NuGet

PM> Install-Package Spire.Doc

Il ne fait aucun doute que le document Word est l'un des types de fichiers de documents les plus populaires aujourd'hui. Parce que le document Word est un format de fichier idéal pour générer des lettres, des mémos, des rapports, des dissertations, des romans et des magazines, etc. Dans cet article, vous apprendrez à créer un document Word simple à partir de zéro en C# et VB.NET en utilisant Spire.Doc for .NET.

Spire.Doc for .NET fournit la classe Document pour représenter un modèle de document Word, permettant aux utilisateurs de lire et de modifier des documents existants ou d'en créer de nouveaux. Un document Word doit contenir au moins une section (représentée par la classe Section) et chaque section est un conteneur pour les éléments Word de base tels que les paragraphes, les tableaux, les en-têtes, les pieds de page, etc. Le tableau ci-dessous répertorie les classes et méthodes importantes impliquées dans ce didacticiel.

Member Description
Classe de documents Représente un modèle de document Word.
Classe de section Représente une section dans un document Word.
Classe de paragraphe Représente un paragraphe dans une section.
Classe ParagraphStyle Définit les informations de formatage de la police pouvant être appliquées à un paragraphe.
Méthode Section.AddParagraph() Ajoute un paragraphe à une section.
Méthode Paragraph.AppendText() Ajoute du texte à un paragraphe à la fin.
Méthode Paragraph.ApplyStyle() Applique un style à un paragraphe.
Méthode Document.SaveToFile() Enregistre le document dans un fichier Word avec une extension .doc ou .docx. Cette méthode prend également en charge l'enregistrement du document au format PDF, XPS, HTML, PLC, etc.

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Créer un document Word simple

Voici les étapes pour créer un document Word simple contenant plusieurs paragraphes à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Ajoutez une section à l'aide de la méthode Document.AddSection().
  • Définissez les marges de la page via la propriété Section.PageSetUp.Margins.
  • Ajoutez plusieurs paragraphes à la section à l'aide de la méthode Section.AddParagraph().
  • Ajoutez du texte aux paragraphes à l'aide de la méthode Paragraph.AppendText().
  • Créez un objet ParagraphStyle et appliquez-le à un paragraphe spécifique à l'aide de la méthode Paragraph.ApplyStyle().
  • Enregistrez le document dans un fichier Word à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace CreateWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Set the page margins
                section.PageSetup.Margins.All = 40f;
    
                //Add a paragraph as title
                Paragraph titleParagraph = section.AddParagraph();
                titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
    
                //Add two paragraphs as body
                Paragraph bodyParagraph_1 = section.AddParagraph();
                bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                    "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                    "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
    
    
                Paragraph bodyParagraph_2 = section.AddParagraph();
                bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                             "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                             "document creation capabilities into any developers' .NET applications.");
    
                //Create a style for title paragraph
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "Times New Roman";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                titleParagraph.ApplyStyle("titleStyle");
    
                //Create a style for body paragraphs
                ParagraphStyle style2 = new ParagraphStyle(doc);
                style2.Name = "paraStyle";
                style2.CharacterFormat.FontName = "Times New Roman";
                style2.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style2);
                bodyParagraph_1.ApplyStyle("paraStyle");
                bodyParagraph_2.ApplyStyle("paraStyle");
    
                //Set the horizontal alignment of paragraphs
                titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
                bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
    
                //Set the first line indent
                bodyParagraph_1.Format.FirstLineIndent = 30;
                bodyParagraph_2.Format.FirstLineIndent = 30;
    
                //Set the after spacing
                titleParagraph.Format.AfterSpacing = 10;
                bodyParagraph_1.Format.AfterSpacing = 10;
    
                //Save to file
                doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Word Document

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 31 July 2023 06:51

C#/VB.NET: Converter Word para XPS

Instalado via NuGet

PM> Install-Package Spire.Doc

Links Relacionados

XPS (XML Paper Specification) é um formato de documento de layout fixo projetado para preservar a fidelidade do documento e fornecer aparência de documento independente do dispositivo. É semelhante ao PDF, mas é baseado em XML em vez de PostScript. Se você deseja salvar um documento do Word em um formato de arquivo de layout fixo, o XPS seria uma opção. Este artigo demonstrará como converter documentos do Word em XPS em C# e VB.NET usando o Spire.Doc for .NET.

Instalar o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Converter Word para XPS em C# e VB.NET

A seguir estão as etapas detalhadas para converter um documento do Word em XPS usando o Spire.Doc for .NET:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Salve o documento do Word em XPS usando o método Document.SaveToFile(string filePath, FileFormat fileFormat).
  • C#
  • VB.NET
using Spire.Doc;
    namespace ConvertWordToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document doc = new Document();
                //Load a Word document
                doc.LoadFromFile("Sample.docx");
                //convert the document to XPS
                doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
            }
        }
    }

C#/VB.NET: Convert Word to XPS

Solicitar uma licença temporária

Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Установлено через NuGet

PM> Install-Package Spire.Doc

Ссылки по теме

XPS (XML Paper Specification) — это формат документа с фиксированным макетом, предназначенный для сохранения точности документа и обеспечения независимого от устройства внешнего вида документа. Он похож на PDF, но основан на XML, а не на PostScript. Если вы хотите сохранить документ Word в формате файла с фиксированным макетом, вам подойдет XPS. В этой статье показано, как преобразовать документы Word в XPS на C# и VB.NET с помощью Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Преобразование Word в XPS в C# и VB.NET

Ниже приведены подробные инструкции по преобразованию документа Word в XPS с помощью Spire.Doc for .NET:

  • Инициализировать экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Сохраните документ Word в XPS, используя метод Document.SaveToFile(string filePath, FileFormat fileFormat).
  • C#
  • VB.NET
using Spire.Doc;
    namespace ConvertWordToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document doc = new Document();
                //Load a Word document
                doc.LoadFromFile("Sample.docx");
                //convert the document to XPS
                doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
            }
        }
    }

C#/VB.NET: Convert Word to XPS

Подать заявку на временную лицензию

Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.

Смотрите также