Passer au contenu du pied de page
UTILISATION D'IRONWORD

Comment exporter un document en Word dans C#

Microsoft Word is a ubiquitous tool for creating and editing documents, widely used across various industries for its versatile features and user-friendly interface. In software development, there are often scenarios where we need to programmatically generate Word documents, either for reporting, documentation, or data presentation purposes.

In this guide, we'll explore how to create a new C# Console Application and how to export data to MS Word documents in C# using IronWord, a powerful library for manipulating Word documents programmatically.

How to Export Document to Word in C#

  1. Create a New C# Visual Studio Project.
  2. Install the C# Word library to export data to Word.
  3. Import dependencies for the Word Library.
  4. Create a new Word Document using the "new WordDocument(paragraph)" method.
  5. Save the newly created Word document with the "SaveAs()" function.

Create a New C# Console Application

To create a new C# Console application in Visual Studio, follow these steps.

  1. Open Visual Studio. On the startup screen, select the "Create a new project" option.

How to Export Document to Word in C#: Figure 1 - Visual Studio

  1. A new window will appear containing the recent templates and all the templates available. Select the "Console App" option and click on Next.

How to Export Document to Word in C#: Figure 2 - Console App

  1. In the newly appeared window, write the project name and select the location. Click on Next, and then after selecting the version, click on Create.

IronWord

IronWord is a .NET library that provides a convenient API for working with Word documents in C#. It allows developers to create Word documents, modify existing Word documents, and export Word documents seamlessly within their C# applications. With IronWord, you can generate Word documents dynamically based on data from various sources, such as databases, APIs, or user inputs.

IronWord fosters creativity and expression, providing a space where emerging voices mingle with seasoned wordsmiths. Through its commitment to literary excellence and diversity, IronWord cultivates a rich tapestry of narratives that resonate with audiences worldwide, igniting imaginations and sparking conversations that endure beyond the page.

Install IronWord

You can easily install IronWord using the NuGet Package Manager by following these steps.

  1. In Visual Studio, open the NuGet Package Manager window and go to the Browse tab.
  2. In the Browse tab, write IronWord in the search bar and press enter.
  3. A list of packages will appear. Select the latest package and click on Install.

How to Export Document to Word in C#: Figure 3 - IronWord

Just like that, IronWord is installed and ready to use.

Export Data to a Word Document

Let's dive into a practical example of how to export data to a Word document using IronWord in C#. Consider the following code snippet:

using IronWord;
using IronWord.Models;

System.Console.WriteLine("Enter the Text to export it to word document");
var userInput = System.Console.ReadLine();

// Create textRun which is a part of a paragraph content
Text textRun = new Text(userInput);
Paragraph paragraph = new Paragraph();
paragraph.AddChild(textRun);

// Create a new document object and add the paragraph to it
WordDocument doc = new WordDocument(paragraph);

// Export document to "document.docx" file
doc.SaveAs("document.docx");
using IronWord;
using IronWord.Models;

System.Console.WriteLine("Enter the Text to export it to word document");
var userInput = System.Console.ReadLine();

// Create textRun which is a part of a paragraph content
Text textRun = new Text(userInput);
Paragraph paragraph = new Paragraph();
paragraph.AddChild(textRun);

// Create a new document object and add the paragraph to it
WordDocument doc = new WordDocument(paragraph);

// Export document to "document.docx" file
doc.SaveAs("document.docx");
Imports IronWord
Imports IronWord.Models

System.Console.WriteLine("Enter the Text to export it to word document")
Dim userInput = System.Console.ReadLine()

' Create textRun which is a part of a paragraph content
Dim textRun As New Text(userInput)
Dim paragraph As New Paragraph()
paragraph.AddChild(textRun)

' Create a new document object and add the paragraph to it
Dim doc As New WordDocument(paragraph)

' Export document to "document.docx" file
doc.SaveAs("document.docx")
$vbLabelText   $csharpLabel

In this example, we're creating a simple Word document containing a single paragraph with the text from the user. Let's break down the code step by step:

  1. Importing Required Libraries: We begin by importing the necessary namespaces from IronWord.
  2. Creating Text Content: We create a Text object representing the text content we want to include in the Word document. In this case, it's the userInput.
  3. Creating a Paragraph: Next, we create a Paragraph object and add the Text object (textRun) to it as a child element. A paragraph in Word typically contains one or more text runs.
  4. Creating a Word Document: We instantiate a new WordDocument object, passing the paragraph we created as a parameter. This initializes a new Word document with the specified content.
  5. Exporting the Document: Finally, we call the SaveAs method on the WordDocument object to export the document to a .docx file named "document.docx."

This example demonstrates the basic workflow for exporting data to a Word document using IronWord. However, it's important to note that you can customize the existing Word document content and structure according to your specific requirements. For instance, you can add multiple paragraphs, format text, insert tables, images, headers, footers, and more.

Console Screenshot

How to Export Document to Word in C#: Figure 4 - Export Data Console Output

Output Word Document

How to Export Document to Word in C#: Figure 5 - Create Word Document Output

Conclusion

In summary, IronWord provides a powerful and flexible solution for exporting data to Word documents in C#. Whether you're generating simple reports, complex documents, or dynamic content, IronWord simplifies the process and empowers developers to create high-quality Word documents programmatically. By leveraging its features and capabilities, you can streamline document generation workflows and deliver compelling content to your users.

To learn more techniques to automate Microsoft Word document generation, visit the following link.

Questions Fréquemment Posées

Comment puis-je exporter des données vers un document Word en C#?

Vous pouvez utiliser IronWord pour exporter des données vers un document Word en C# en créant une Application Console C#, en installant IronWord via le Gestionnaire de Paquets NuGet, en important les bibliothèques nécessaires et en utilisant l'API pour créer et enregistrer un document Word avec vos données.

Quels sont les avantages d'utiliser une bibliothèque .NET pour la création de documents Word?

Utiliser une bibliothèque .NET comme IronWord pour la création de documents Word permet aux développeurs d'automatiser la génération de documents de haute qualité de manière programmatique, rendant les flux de travail plus efficaces et adaptables à des exigences spécifiques sans dépendre de Microsoft Interop.

Comment formater le texte et ajouter des images à un document Word en C#?

Avec IronWord, vous pouvez formater le texte en définissant les styles, tailles et couleurs de police, et ajouter des images en les insérant dans le document à l'aide de l'API. Cela permet une personnalisation riche des documents dans les applications C#.

IronWord peut-il être utilisé pour la génération dynamique de documents?

Oui, IronWord permet la génération dynamique de documents en vous permettant de créer des documents Word basés sur des données de diverses sources telles que des bases de données ou des informations entrées par les utilisateurs, qui peuvent être adaptées pour répondre à des besoins spécifiques.

Quelles étapes sont impliquées dans la création d'un document Word avec IronWord?

Pour créer un document Word avec IronWord, commencez par configurer une Application Console C#, installez IronWord via NuGet, importez la bibliothèque, créez des objets de texte et de paragraphe, et utilisez la méthode SaveAs pour exporter le document.

Comment IronWord simplifie-t-il la création de documents Word en C#?

IronWord simplifie la création de documents Word en fournissant une API simple qui permet aux développeurs de créer, manipuler et exporter facilement des documents Word par programmation, réduisant ainsi la complexité et augmentant la productivité.

Est-il possible de créer un document Word à partir de données entrées par l'utilisateur en C#?

Oui, avec IronWord, vous pouvez créer un document Word à partir de données entrées par l'utilisateur en capturant l'entrée, en créant un objet Texte, en l'ajoutant à un Paragraphe, puis en l'exportant en tant que fichier .docx en utilisant l'API IronWord.

Comment puis-je résoudre les problèmes courants lors de l'exportation vers Word en C#?

Lors d'un dépannage de problèmes avec l'exportation vers Word en utilisant IronWord, assurez-vous que toutes les bibliothèques nécessaires sont importées, que la bonne version de la bibliothèque est installée via NuGet, et que vos types de données sont compatibles avec les méthodes de l'API utilisées.

Quelles sont certaines applications pratiques de la génération programmatique de documents Word?

La génération programmatique de documents Word avec IronWord est utile pour créer des rapports automatisés, de la documentation et des documents de présentation de données, en particulier lorsqu'il s'agit de grands ensembles de données ou d'informations mises à jour fréquemment.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite