C#/VB.NET: Word-Dokumente zusammenführen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
Lange Arbeiten oder Forschungsberichte werden häufig von mehreren Personen gemeinsam erstellt. Um Zeit zu sparen, kann jede Person an den ihnen zugewiesenen Teilen in separaten Dokumenten arbeiten und diese Dokumente nach Abschluss der Bearbeitung zu einem zusammenführen. Abgesehen vom manuellen Kopieren und Einfügen von Inhalten aus einem Word-Dokument in ein anderes werden in diesem Artikel die folgenden zwei Möglichkeiten zum programmgesteuerten Zusammenführen von Word-Dokumenten mit Spire.Doc for .NET .
- Führen Sie Dokumente zusammen, indem Sie die gesamte Datei einfügen
- Dokumente durch Klonen von Inhalten zusammenführen
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
Führen Sie Dokumente zusammen, indem Sie die gesamte Datei einfügen
Die von Spire.Doc for .NET bereitgestellte Methode Document.InsertTextFromFile() ermöglicht das Zusammenführen von Word-Dokumenten, indem andere Dokumente vollständig in ein Dokument eingefügt werden. Bei dieser Methode beginnt der Inhalt des eingefügten Dokuments auf einer neuen Seite. Die detaillierten Schritte sind wie folgt:
- Erstellen Sie eine Document-Instanz.
- Laden Sie das ursprüngliche Word-Dokument mit der Methode Document.LoadFromFile().
- Fügen Sie mit der Methode Document.InsertTextFromFile() ein weiteres Word-Dokument vollständig in das Originaldokument ein.
- Speichern Sie das Ergebnisdokument mit der Methode 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);
}
}
}

Dokumente durch Klonen von Inhalten zusammenführen
Wenn Sie Dokumente zusammenführen möchten, ohne eine neue Seite zu beginnen, können Sie den Inhalt anderer Dokumente klonen und am Ende des Originaldokuments hinzufügen. Die detaillierten Schritte sind wie folgt:
- Laden Sie zwei Word-Dokumente.
- Durchlaufen Sie das zweite Dokument, um alle Abschnitte mithilfe der Document.Sections-Eigenschaft abzurufen, und durchlaufen Sie dann alle Abschnitte, um deren untergeordnete Objekte mithilfe der Section.Body.ChildObjects-Eigenschaft abzurufen.
- Rufen Sie den letzten Abschnitt des ersten Dokuments mit der Eigenschaft „Document.LastSection“ ab und fügen Sie dann die untergeordneten Objekte mit der Methode „LastSection.Body.ChildObjects.Add()“ zum letzten Abschnitt des ersten Dokuments hinzu.
- Speichern Sie das Ergebnisdokument mit der Methode 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);
}
}
}

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.
C#/VB.NET: fusionar documentos de Word
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
Los documentos largos o los informes de investigación a menudo se completan en colaboración por varias personas. Para ahorrar tiempo, cada persona puede trabajar en sus partes asignadas en documentos separados y luego combinar estos documentos en uno solo después de terminar la edición. Además de copiar y pegar manualmente el contenido de un documento de Word a otro, este artículo demostrará las siguientes dos formas de fusionar documentos de Word mediante programación usando Spire.Doc for .NET .
- Combinar documentos insertando el archivo completo
- Fusionar documentos mediante la clonación de contenidos
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
Combinar documentos insertando el archivo completo
El método Document.InsertTextFromFile() proporcionado por Spire.Doc for .NET permite fusionar documentos de Word insertando otros documentos por completo en un documento. Usando este método, el contenido del documento insertado comenzará desde una nueva página. Los pasos detallados son los siguientes:
- Cree una instancia de documento.
- Cargue el documento de Word original utilizando el método Document.LoadFromFile().
- Inserte otro documento de Word completamente en el documento original utilizando el método Document.InsertTextFromFile().
- Guarde el documento de resultados utilizando el método 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);
}
}
}

Fusionar documentos mediante la clonación de contenidos
Si desea fusionar documentos sin comenzar una nueva página, puede clonar el contenido de otros documentos para agregarlos al final del documento original. Los pasos detallados son los siguientes:
- Cargue dos documentos de Word.
- Recorra el segundo documento para obtener todas las secciones usando la propiedad Document.Sections y luego recorra todas las secciones para obtener sus objetos secundarios usando la propiedad Section.Body.ChildObjects.
- Obtenga la última sección del primer documento usando la propiedad Document.LastSection y luego agregue los objetos secundarios a la última sección del primer documento usando el método LastSection.Body.ChildObjects.Add().
- Guarde el documento de resultados utilizando el método 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);
}
}
}

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.
C#/VB.NET: Word 문서 병합
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
긴 논문이나 연구 보고서는 종종 여러 사람이 공동으로 작성합니다. 시간을 절약하기 위해 각 사람은 별도의 문서에서 할당된 부분을 작업한 다음 편집을 마친 후 이러한 문서를 하나로 병합할 수 있습니다. 한 Word 문서에서 다른 문서로 콘텐츠를 수동으로 복사하여 붙여넣는 것 외에도 이 기사에서는 Spire.Doc for .NET을 사용하여 프로그래밍 방식으로 Word 문서를 병합하는 다음 두 가지 방법을 보여줍니다.
Spire.Doc for .NET 설치
먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
전체 파일을 삽입하여 문서 병합
Spire.Doc for .NET에서 제공하는 Document.InsertTextFromFile() 메서드를 사용하면 다른 문서를 문서에 완전히 삽입하여 Word 문서를 병합할 수 있습니다. 이 방법을 사용하면 삽입된 문서의 내용이 새 페이지에서 시작됩니다. 자세한 단계는 다음과 같습니다.
- 문서 인스턴스를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 원본 Word 문서를 로드합니다.
- Document.InsertTextFromFile() 메서드를 사용하여 원본 문서에 다른 Word 문서를 완전히 삽입합니다.
- 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);
}
}
}

콘텐츠를 복제하여 문서 병합
새 페이지를 시작하지 않고 문서를 병합하려는 경우 다른 문서의 내용을 복제하여 원본 문서 끝에 추가할 수 있습니다. 자세한 단계는 다음과 같습니다.
- 두 개의 Word 문서를 로드합니다.
- 두 번째 문서를 반복하여 Document.Sections 속성을 사용하여 모든 섹션을 가져온 다음 모든 섹션을 반복하여 Section.Body.ChildObjects 속성을 사용하여 하위 개체를 가져옵니다.
- Document.LastSection 속성을 사용하여 첫 번째 문서의 마지막 섹션을 가져온 다음 LastSection.Body.ChildObjects.Add() 메서드를 사용하여 첫 번째 문서의 마지막 섹션에 자식 개체를 추가합니다.
- 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);
}
}
}

임시 면허 신청
생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: unisci documenti Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Articoli lunghi o rapporti di ricerca sono spesso completati in collaborazione da più persone. Per risparmiare tempo, ogni persona può lavorare sulle parti assegnate in documenti separati e quindi unire questi documenti in uno solo dopo aver terminato la modifica. Oltre a copiare e incollare manualmente il contenuto da un documento di Word a un altro, questo articolo illustrerà i seguenti due modi per unire i documenti di Word a livello di codice utilizzando Spire.Doc for .NET .
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
Unisci documenti inserendo l'intero file
Il metodo Document.InsertTextFromFile() fornito da Spire.Doc for .NET consente di unire documenti Word inserendo altri documenti interamente in un documento. Utilizzando questo metodo, il contenuto del documento inserito partirà da una nuova pagina. I passaggi dettagliati sono i seguenti:
- Crea un'istanza di Documento.
- Carica il documento Word originale utilizzando il metodo Document.LoadFromFile().
- Inserisci un altro documento Word interamente nel documento originale utilizzando il metodo Document.InsertTextFromFile().
- Salva il documento del risultato utilizzando il metodo 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);
}
}
}

Unisci documenti clonando i contenuti
Se desideri unire documenti senza iniziare una nuova pagina, puoi clonare il contenuto di altri documenti da aggiungere alla fine del documento originale. I passaggi dettagliati sono i seguenti:
- Carica due documenti Word.
- Eseguire il ciclo del secondo documento per ottenere tutte le sezioni utilizzando la proprietà Document.Sections, quindi eseguire il ciclo di tutte le sezioni per ottenere i relativi oggetti figlio utilizzando la proprietà Section.Body.ChildObjects.
- Ottieni l'ultima sezione del primo documento utilizzando la proprietà Document.LastSection, quindi aggiungi gli oggetti figlio all'ultima sezione del primo documento utilizzando il metodo LastSection.Body.ChildObjects.Add().
- Salva il documento del risultato utilizzando il metodo 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);
}
}
}

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.
C#/VB.NET : fusionner des documents Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
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);
}
}
}

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

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.
- C#/VB.NET : insérer des listes dans un document Word
- C#/VB.NET : détecter et supprimer les macros VBA des documents Word
- C#/VB.NET : insérer des équations mathématiques dans des documents Word
- C#/VB.NET : comparer deux documents Word
- C#/VB.NET : accepter ou rejeter les modifications suivies dans Word
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);
}
}
}

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.
C#/VB.NET: создание документа Word
Установлено через 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);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: Erstellen Sie ein Word-Dokument
Inhaltsverzeichnis
Ü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);
}
}
}

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.
C#/VB.NET: crear un documento de Word
Tabla de contenido
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);
}
}
}

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

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