Saltar al pie de página
USANDO IRONWORD

Cómo Leer un Archivo Word Usando C#

In today's era, Microsoft Word documents are synonymous with office work and professional and personal communication. Hence, programmatically manipulating Word documents is critical for developers looking to automate tasks to display to users in their applications. Although there are many available libraries, not all are as robust as the others. However, one such contender that stands out from the rest is IronWord. IronWord is a reliable and robust C# Word DOCX library that is easy to use and understand, and simplifies working with Word documents.

This article will explore how we can quickly utilize IronWord to read Word documents with short examples.

How To Read a Word File Using C#

  1. Create a Console Application in Visual Studio

  2. Install IronWord C# DOCX library

  3. Create a new Word document using the WordDocument class

  4. Add text to the Word document

  5. Loop through each paragraph using the Paragraph class

  6. Display the contents

IronWord: The C# DOCX Library

IronWord: The C# DOCX Library

IronWord is a flexible and scalable library with a straightforward and easy-to-use API that eliminates the hassle of integrating Word documents into applications. Whether you want to add and integrate a simple text word document to your application or create complex tables and reports to display to users, IronWord has everything covered.

Here are its most notable features:

  1. Document Manipulation: IronWord allows developers to manipulate Word documents with ease. Whether users want to insert paragraphs of text or more complex structures such as tables and images, IronWord can do it all.

  2. Cross-Platform Support and Compatibility: IronWord is designed to be flexible and supports developers on multiple platforms. It supports various .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), .NET Framework (4.6.2+), and even Azure. Furthermore, developers can utilize IronWord on different platforms and systems, including but not limited to Windows, Linux, macOS, and Android. It covers the most common platforms and allows developers to build cross-platform applications quickly.

  3. Independence from Microsoft Office: One common trouble when integrating Word documents in .NET applications is that popular libraries such as Interop require a licensed installation of Microsoft Office. However, IronWord alleviates that problem by being independent of that restriction. Developers can fully leverage the power of Word documents without being restricted by the license and installation of Microsoft Word.

  4. Formatting Options: IronWord offers extensive support for formatting and styling, allowing developers to make the document unique. Developers can apply fonts to their text, colors, alignments, and other complex formatting, such as table styles.

  5. Ease of Use and Extensive Support: Along with an easy-to-understand API and straightforward method calls, IronWord also provides extension API references and code examples to help developers determine the most optimal way to utilize IronWord.

Creating a New Console Project in Visual Studio

Before we dive into the example, let's start by creating a blank console project in Visual Studio.

Click console app when creating a new project

We then provide a name and a save location for the project.

Specify the name and location path for the project.

Next, select the .NET framework that you will be using. In this example, I will be using .NET 8.0.

Select the desired .NET framework and click on Create.

After creating and setting up the new console project, let's install our C# word library, IronWord.

Installing IronWord

There are two ways to install IronWord.

1. Installing via NuGet Package Manager

To install it through the NuGet Package Manager, click on tools and then Manage NuGet Packages for Solution. We then search for IronWord in the search bar and install **IronWord**.

Install IronWord using the Manage NuGet Package for Solution by searching IronWord in the search bar of NuGet Package Manager, then select the project and click on the Install button.

2. Installing via NuGet Package Manager Console

An alternative method is to install it via the NuGet Package Manager Console. To do so, run the following command in the console:

Install-Package IronWord

License Key

Please note that IronWord doesn't work without a licensing key; you can obtain one here as part of a free trial.

After obtaining a trial key, ensure this variable is set in your project.

// Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
// Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
' Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY"
$vbLabelText   $csharpLabel

Reading Word Documents in C#

After installing the prerequisites, we will demonstrate the simplicity of reading a Microsoft Word document using IronWord in the following code.

First, we import the necessary namespaces. Using IronWord, we create a new document and add sample text. We then access the paragraphs and text using the WordDocument object to print out the text within the Word document.

using IronWord;
using IronWord.Models;

#region Licensing
// Set the IronWord license key before using the IronWord functionalities
IronWord.License.LicenseKey = "YOUR-KEY-HERE";
#endregion

// Create text run with sample text
Text textRunExample = new Text("Sample text");

// Create a paragraph and add the text run to it
Paragraph paragraphExample = new Paragraph();
paragraphExample.AddChild(textRunExample);

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

// Export the document as a DOCX file
doc.SaveAs("document.docx");

// Access paragraphs and text runs within the document
foreach (Paragraph paragraph in doc.Paragraphs)
{
    foreach (Text textRun in paragraph.Texts)
    {
        // Access text content
        string content = textRun.Text;
        // Display the content to the console
        Console.WriteLine(content);
    }
}
using IronWord;
using IronWord.Models;

#region Licensing
// Set the IronWord license key before using the IronWord functionalities
IronWord.License.LicenseKey = "YOUR-KEY-HERE";
#endregion

// Create text run with sample text
Text textRunExample = new Text("Sample text");

// Create a paragraph and add the text run to it
Paragraph paragraphExample = new Paragraph();
paragraphExample.AddChild(textRunExample);

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

// Export the document as a DOCX file
doc.SaveAs("document.docx");

// Access paragraphs and text runs within the document
foreach (Paragraph paragraph in doc.Paragraphs)
{
    foreach (Text textRun in paragraph.Texts)
    {
        // Access text content
        string content = textRun.Text;
        // Display the content to the console
        Console.WriteLine(content);
    }
}
Imports IronWord
Imports IronWord.Models

#Region "Licensing"
' Set the IronWord license key before using the IronWord functionalities
IronWord.License.LicenseKey = "YOUR-KEY-HERE"
'#End Region

' Create text run with sample text
Dim textRunExample As New Text("Sample text")

' Create a paragraph and add the text run to it
Dim paragraphExample As New Paragraph()
paragraphExample.AddChild(textRunExample)

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

' Export the document as a DOCX file
doc.SaveAs("document.docx")

' Access paragraphs and text runs within the document
For Each paragraph As Paragraph In doc.Paragraphs
	For Each textRun As Text In paragraph.Texts
		' Access text content
		Dim content As String = textRun.Text
		' Display the content to the console
		Console.WriteLine(content)
	Next textRun
Next paragraph
$vbLabelText   $csharpLabel

Let's explore the methods and parameters to read word files from the above code.

  1. We first create a Text object and assign the string "Sample text" to it.

  2. We then instantiate a Paragraph object and add the "textRunExample" to it.

  3. We also instantiate a WordDocument object, name it WordDocument doc, and pass the paragraphExample to it to create a new Word document containing the paragraph.

  4. The code saves the Word document with the file name "document.docx" for later use.

  5. To access the paragraphs in the Word document we just created, we access the "Paragraphs" property of the WordDocument object. The "Paragraphs" property is a list. Hence, we call a foreach loop to iterate through it.

  6. To obtain the text within the paragraph, we access the "Texts" property of Paragraphs. This also returns a list of Text.

  7. Finally, we assign the Text to a string variable named "content" and print it out to the console.

Console output

Console output displaying the text read from the Word Document doc.

Reading an existing Word document in C#

In the previous example, we programmatically created a new Word document and read its content. We can follow similar steps to read an existing Word document by making a few code changes.

Input Document

Input Example: Long form Word document

using IronWord;
using IronWord.Models;

#region Licensing
// Set the IronWord license key before using the IronWord functionalities
IronWord.License.LicenseKey = "YOUR-KEY-HERE";
#endregion

// Load an existing Word document
WordDocument doc = new WordDocument("existing_document.docx");

// Access paragraphs and text runs within the document
foreach (Paragraph paragraph in doc.Paragraphs)
{
    foreach (Text textRun in paragraph.Texts)
    {
        // Access text content
        string content = textRun.Text;
        // Display the content to the console
        Console.WriteLine(content);
    }
}
using IronWord;
using IronWord.Models;

#region Licensing
// Set the IronWord license key before using the IronWord functionalities
IronWord.License.LicenseKey = "YOUR-KEY-HERE";
#endregion

// Load an existing Word document
WordDocument doc = new WordDocument("existing_document.docx");

// Access paragraphs and text runs within the document
foreach (Paragraph paragraph in doc.Paragraphs)
{
    foreach (Text textRun in paragraph.Texts)
    {
        // Access text content
        string content = textRun.Text;
        // Display the content to the console
        Console.WriteLine(content);
    }
}
Imports IronWord
Imports IronWord.Models

#Region "Licensing"
' Set the IronWord license key before using the IronWord functionalities
IronWord.License.LicenseKey = "YOUR-KEY-HERE"
'#End Region

' Load an existing Word document
Dim doc As New WordDocument("existing_document.docx")

' Access paragraphs and text runs within the document
For Each paragraph As Paragraph In doc.Paragraphs
	For Each textRun As Text In paragraph.Texts
		' Access text content
		Dim content As String = textRun.Text
		' Display the content to the console
		Console.WriteLine(content)
	Next textRun
Next paragraph
$vbLabelText   $csharpLabel

The main difference between the two examples is the parameter passed into the WordDocument object. Instead of creating a new document, we load an existing Word file into it. The rest is the same as the other example.

Console output

Console Output

Conclusion

IronWord licensing information

Throughout the examples, we demonstrated how straightforward it is to use the IronWord library to manipulate and read Word documents programmatically in C#. The flexibility and scalability of the IronWord library make it a valuable tool that allows developers to use IronWord in practical, real-life examples, such as filling templates, generating reports, and batch-processing documents. Understanding how Word integrates with applications is valuable as it provides developers with more solutions to their problems.

Furthermore, developers can test IronWord's extensive features for a period of time before purchasing, as it offers a free trial license. Along with ease of use, IronWord also comes with thorough documentation and 24/5 support for developers, alleviating the constant frustration developers might face in the face of production. We also offer various tutorials and a range of code examples for reference to help you get started with IronWord.

After testing out various aspects of IronWord using a trial-license, you can purchase our Lite developer license that starts at $599 and goes upwards from Lite to Professional. Please refer to our licensing page for more information.

Preguntas Frecuentes

¿Cómo puedo leer un documento de Word usando C#?

Puedes usar IronWord para leer un documento de Word en C#. Simplemente carga el documento utilizando la clase WordDocument, luego itera a través de párrafos y ejecuciones de texto para acceder y mostrar el contenido de texto.

¿Cuál es una biblioteca confiable en C# para leer documentos de Word?

IronWord es una biblioteca confiable en C# diseñada para leer y manipular documentos de Word. Ofrece una API sencilla que simplifica la integración de funcionalidades de documentos de Word en aplicaciones.

¿Necesito tener Microsoft Office instalado para leer documentos de Word en C#?

No, IronWord no requiere que Microsoft Office esté instalado. Funciona de manera independiente, permitiéndote manipular documentos de Word sin necesitar una versión con licencia de Office.

¿Cómo puedo instalar una biblioteca en C# para leer documentos de Word en Visual Studio?

Puedes instalar IronWord a través del Gestor de Paquetes NuGet en Visual Studio buscando 'IronWord' y seleccionando 'Instalar', o utilizando la Consola del Gestor de Paquetes NuGet con el comando Install-Package IronWord.

¿Qué plataformas son compatibles con IronWord para la manipulación de documentos de Word?

IronWord es compatible con una variedad de plataformas, incluidas .NET Core (8, 7, 6, 5 y 3.1+), .NET Standard (2.0+), .NET Framework (4.6.2+), y Azure, y es compatible con Windows, Linux, macOS y Android.

¿Puedo manipular documentos de Word existentes usando una biblioteca en C#?

Sí, IronWord te permite leer y modificar tanto nuevos como existentes documentos de Word de manera programática, ofreciendo control total sobre el contenido y la estructura del documento.

¿Hay una prueba gratuita disponible para IronWord?

Sí, IronWord ofrece una licencia de prueba gratuita. Los desarrolladores pueden usar esta prueba para explorar sus características y evaluar su idoneidad para sus proyectos antes de comprar una licencia completa.

¿Cómo puedo convertir documentos de Word a otros formatos usando C#?

Puedes usar IronWord para convertir documentos de Word a varios formatos al aprovechar su API para exportar documentos a formatos como PDF, HTML y más, aunque los detalles de la conversión pueden variar.

¿Cuáles son algunos casos de uso comunes para IronWord en aplicaciones C#?

IronWord se utiliza comúnmente para tareas como completar plantillas, generar informes, procesar documentos por lotes e integrar funcionalidades de documentos de Word en aplicaciones .NET.

¿Qué opciones de soporte están disponibles para los usuarios de IronWord?

IronWord proporciona soporte 24/5, junto con documentación completa, tutoriales y ejemplos de código, para ayudar a los desarrolladores a utilizar efectivamente la biblioteca.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más