Passer au contenu du pied de page
UTILISATION D'IRONWORD

Comment créer un fichier DOCX en C#

Many applications in today's digital environment require the ability to generate and alter documents automatically. The ability to create and work with DOCX files is useful whether you're building an enterprise-level reporting system, a document management system, or just automating repetitive activities. In this tutorial, we'll dive into the world of C# document generation and examine the robust libraries and programming methods that can be used in C# to create DOCX files.

How to Create DOCX File in C#

  1. Install the NuGet package IronWord.
  2. Take the required namespaces and import them from IronWord.
  3. To generate document files, add a new TextRun.
  4. Make a new Body and Document.
  5. Fill the Body with content (paragraphs, tables, etc.).
  6. Using WordDocument, create a new WordDocument.
  7. Assigning the Document object to the TextRun, Paragraph Document property will save the modifications.

Getting to Know the DOCX Format

Before delving into the coding, let us clarify what a DOCX file is. Microsoft Word and other Word processing programs save documents in the DOCX file format. It is based on the ZIP-compressed XML-based [Office Open XML (OOXML) standard](https://en.wikipedia.org/wiki/Office_Open_XML#:~:text=Office%20Open%20XML%20(also%20informally,initial%20version%20as%20ECMA%2D376.). This allows utilizing APIs from Microsoft and other developers to manipulate it programmatically relatively simply.

IronWord

Iron Software created the Word document library known as IronWord. When it comes to offering strong capabilities for Word document manipulation in .NET applications, IronWord shines. To help .NET C# developers include the ability to create, read, and modify Word and DOCX documents in their programs, IronWord is a robust Word document library.

Features of IronWord

  • Create and edit DOC and DOCX: IronWord eliminates the requirement for Office Interop or Microsoft Word installation by enabling you to create and edit Word documents right within your .NET projects.
  • Open, Edit an existing document, and Save a Word file and Docx: The Word document structure is customizable, including page configuration (background color, margins, paper size, and orientation).
  • Include Words and Pictures: With the simple API, you can quickly add text and graphics to your Word documents.
  • Cross-Platform Support: IronWord is compatible with .NET 8, 7, 6, Core, Standard, or Framework, and is built for C#, F#, and VB.NET. It functions in several environments, such as Docker, iOS, Android, Windows, and Linux.
  • Worldwide, millions of engineers rely on us: IronWord is a component of the Iron Suite, which consists of nine .NET API office document products. Developers use it all over the world to create, view, and modify Word documents.

To know more about IronWord refer here.

Creating a New Project in Visual Studio

To launch the Visual Studio application, use the File menu and choose File. Click "New Project," then choose "Console application."

How to Create DOCX File in C#: Figure 1 - Creating a new project

Enter the project name in the designated text field after choosing the file location. Next, as seen in the sample below, click the Create button and choose the required .NET Framework.

How to Create DOCX File in C#: Figure 2 - Configuring the project name and file path

The Visual Studio project's organization will then depend on the selected application. To add code and construct the application, just open the program.cs file. The internet application, Windows, or console can all be used.

After that, the library may be added and the code tested.

Install IronWord library

Making Use of Visual Studio Tool Select NuGet Package Manager from the Tools Menu. Enter the Package Manager interface to gain access to the package management terminal console.

Install-Package IronWord

After downloading and installing the package, it can now be utilized in the ongoing project.

How to Create DOCX File in C#: Figure 3 - Installing IronWord with the package manager console

There's also the Package Manager method. Installing the package straight into the solution is possible with Visual Studio's NuGet Package Manager option. You can see how to launch the NuGet Package Manager in the image below.

How to Create DOCX File in C#: Figure 4 - How to find the NuGet package manager

Use the NuGet website's search box to locate packages. All we need to do is look up "IronWord" in the package manager, as the screenshot below illustrates:

How to Create DOCX File in C#: Figure 5 - Installing IronWord with the NuGet package manager

The list of relevant search results is displayed in the image above. To install the software on your machine, simply adjust these settings.

Create DOCX Using IronWord

Instantiate a WordDocument object to start a new Word document. To initialize the document, you can use any object that makes up the document structure, like a paragraph, table, or section. Here's an easy illustration in the following code snippet:

using IronWord;
using IronWord.Models;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a text run, which is a portion of the document's text content.
            TextRun textRun = new TextRun("Hello, IronWord!");

            // Create a paragraph and add the text run to it.
            Paragraph paragraph = new Paragraph();
            paragraph.AddTextRun(textRun);

            // Create a new Word document with the paragraph.
            WordDocument doc = new WordDocument(paragraph);

            // Export and save the DOCX file to the specified path.
            doc.SaveAs("document.docx");
        }
    }
}
using IronWord;
using IronWord.Models;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a text run, which is a portion of the document's text content.
            TextRun textRun = new TextRun("Hello, IronWord!");

            // Create a paragraph and add the text run to it.
            Paragraph paragraph = new Paragraph();
            paragraph.AddTextRun(textRun);

            // Create a new Word document with the paragraph.
            WordDocument doc = new WordDocument(paragraph);

            // Export and save the DOCX file to the specified path.
            doc.SaveAs("document.docx");
        }
    }
}
Imports IronWord
Imports IronWord.Models

Namespace ConsoleApp1
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create a text run, which is a portion of the document's text content.
			Dim textRun As New TextRun("Hello, IronWord!")

			' Create a paragraph and add the text run to it.
			Dim paragraph As New Paragraph()
			paragraph.AddTextRun(textRun)

			' Create a new Word document with the paragraph.
			Dim doc As New WordDocument(paragraph)

			' Export and save the DOCX file to the specified path.
			doc.SaveAs("document.docx")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

We can add text to the document with the help of the TextRun class, which allows us to pass the text into the paragraph object with the help of the AddTextRun method. Then we are creating a new WordDocument object to create a new DOCX file. Then, by using the SaveAs method, we can save the new DOCX document in the desired location. Below is the output generated from the above code.

How to Create DOCX File in C#: Figure 6 - Outputted PDF from the previous code

To know more about IronWord code refer here.

Conclusion

We've looked at how to use C# to generate a DOCX document file in this guide. The fundamentals of the DOCX format have been discussed, along with the Open XML SDK and the DocX library, and examples of how to use them to generate, edit, and save DOCX files have been given.

All of these tools and methods will put you in a strong position to handle a variety of document creation tasks in your C# projects. Learning document production in C# is a useful ability that will help you in various situations, whether you're automating report generation, developing document management systems, or just making templates for end users.

For developers working with .NET C#, IronWord is a powerful and adaptable Word document library. It enables developers to read, write, and edit Word (DOCX) documents in their apps with ease. IronWord's user-friendly API makes processing Word documents easier. Without requiring Microsoft Word to be installed or depending on Office Interop, developers may create and edit Word files directly within their .NET projects. Adding text, paragraphs, and other elements to new Word documents is made simple.

IronWord is $799 when it first comes out. In addition, customers who pay a one-year membership fee can receive assistance and updates on products. For a fee, IronWord offers a defense against unrestrained redistribution. To find out more about the approximate cost, go to this page. View more about Iron Software by clicking this link.

Questions Fréquemment Posées

Comment puis-je générer un fichier DOCX en utilisant C# ?

Pour générer un fichier DOCX en utilisant C#, vous pouvez utiliser la bibliothèque IronWord. Commencez par installer le package NuGet IronWord, importez les espaces de noms requis et initiez un objet WordDocument. Vous pouvez ensuite ajouter du contenu en utilisant des méthodes telles que AddTextRun et sauvegarder le document avec la méthode SaveAs.

Quels sont les avantages d'utiliser IronWord pour la génération de fichiers DOCX ?

IronWord offre plusieurs avantages pour la génération de fichiers DOCX, y compris la capacité de créer et modifier des documents sans Microsoft Word, le support multiplateforme, et une API conviviale qui simplifie le processus de création de documents.

Puis-je ajouter des images à un fichier DOCX en utilisant IronWord ?

Oui, IronWord vous permet d'ajouter des images à un fichier DOCX. Vous pouvez utiliser la méthode AddImage pour incorporer des images dans votre document, ce qui peut améliorer l'aspect visuel et la fonctionnalité de vos fichiers DOCX.

Est-il possible de modifier des fichiers DOCX existants avec IronWord ?

Oui, IronWord vous permet de modifier des fichiers DOCX existants. Vous pouvez ouvrir un fichier DOCX en utilisant IronWord, modifier son contenu, sa structure ou son formatage, puis enregistrer les modifications.

IronWord prend-il en charge la génération de documents sur Linux ?

Oui, IronWord prend en charge la génération de documents sur Linux dans le cadre de ses capacités multiplateformes, permettant aux développeurs de créer et manipuler des fichiers DOCX sur divers systèmes d'exploitation, y compris Linux.

Quelles étapes sont nécessaires pour configurer IronWord dans un projet C# ?

La configuration d'IronWord dans un projet C# implique l'installation du package NuGet IronWord via le gestionnaire de packages NuGet, l'importation des espaces de noms nécessaires dans votre code, et l'utilisation de l'API d'IronWord pour réaliser des tâches de création et d'édition de documents.

Comment IronWord gère-t-il la compatibilité des fichiers DOCX ?

IronWord est conçu pour être compatible avec le format DOCX, garantissant que les fichiers créés ou modifiés avec IronWord peuvent être ouverts et utilisés dans Microsoft Word et d'autres traitements de texte compatibles.

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