USO DE IRONWORD

Cómo leer documentos de Word con formato en C#

Actualizado 22 de febrero, 2024
Compartir:

Los documentos de Microsoft Word suelen contener un formato rico, como fuentes, estilos y diversos elementos que los hacen visualmente atractivos. IronWord es una potente biblioteca de Iron Software que dispone de una intuitiva API para documentos Word y Docx en C# y VB.NET. No es necesario instalar Microsoft Office o Word Interop para crear, editar y exportar documentos de Word. IronWord es totalmente compatible con .NET 8, 7, 6, Framework, Core y Azure. Esto significa que la biblioteca no necesita tener Word instalado en la máquina y lee los archivos de forma independiente. Si está trabajando con C# y necesita leer documentos de Word conservando su formato, este tutorial le guiará a través del proceso utilizando la función IronWord biblioteca.

Cómo (en C#) Leer Documento Word Con Formato

  1. Instale la biblioteca IronWord para leer documentos Word.
  2. Cargar 'sample.docx', el documento Word de entrada utilizando la clase WordDocument de la librería IronWord.
  3. Lee los párrafos con formato utilizando un documento Word cargado.
  4. Mostrar los datos extraídos con información de formato en la salida de la consola.

Requisitos previos

  1. Visual Studio: Asegúrese de tener Visual Studio o cualquier otro entorno de desarrollo C# instalado.
  2. NuGet Package Manager: Asegúrese de que puede utilizar NuGet para gestionar paquetes en su proyecto.

Paso 1: Crear un nuevo proyecto C&num

Cree una nueva aplicación de consola C# o utilice un proyecto existente en el que desee leer documentos Word.

Seleccione la plantilla de aplicación de consola y haga clic en Siguiente.

Cómo leer un documento de Word con formato en C#: Figura 1 - Creación de un nuevo proyecto C#

Haga clic en el botón "Siguiente" para indicar el nombre de la solución, el nombre del proyecto y la ruta del código.

Cómo leer un documento de Word con formato en C#: Figura 2 - Configuración del nuevo proyecto

A continuación, seleccione la versión .NET deseada. La mejor práctica es seleccionar siempre la última versión disponible, aunque si su proyecto tiene requisitos específicos, utilice la versión .NET necesaria.

Cómo leer un documento de Word con formato en C#: Figura 3 - Elegir el tipo de versión .NET necesaria

Paso 2: Instalar la biblioteca IronWord

Abra su proyecto C# e instale la biblioteca IronWord utilizando la consola del gestor de paquetes NuGet:

Install-Package IronWord

El paquete NuGet también puede instalarse mediante el gestor de paquetes NuGet de Visual Studio, como se muestra a continuación.

Cómo leer un documento de Word con formato en C#: Figura 4 - Instalación de IronWord a través del gestor de paquetes NuGet

Paso 3: Leer el documento Word con formato

Para leer un archivo de Word, en primer lugar, tenemos que crear un nuevo documento y, a continuación, añadir algo de contenido a la misma como se indica a continuación.

Cómo leer un documento de Word con formato en C#: Figura 5 - Documento de ejemplo creado

Ahora guarda el archivo en el directorio del proyecto y cambia las propiedades del archivo para copiarlo en el directorio de salida

Cómo leer un documento de Word con formato en C#: Figura 6 - Cómo deberían ser las propiedades del archivo

Ahora añade el siguiente fragmento de código al archivo program.cs

using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar docx existente
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; //  leer el texto
                //  Extraer detalles de formato
                if (textRun.Style != null)
                {
                    var fontSize = textRun.Style.FontSize; //  tamaño de letra
                    var isBold = textRun.Style.IsBold;
                    Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
                }
                else
                {
                    //  Imprimir texto sin detalles de formato
                    Console.WriteLine($"\tText: {text}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar docx existente
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; //  leer el texto
                //  Extraer detalles de formato
                if (textRun.Style != null)
                {
                    var fontSize = textRun.Style.FontSize; //  tamaño de letra
                    var isBold = textRun.Style.IsBold;
                    Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
                }
                else
                {
                    //  Imprimir texto sin detalles de formato
                    Console.WriteLine($"\tText: {text}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronWord
Friend Class Program
	Shared Sub Main()
		Try
			'  Cargar docx existente
			Dim sampleDoc = New WordDocument("sample.docx")
			Dim paragraphs = sampleDoc.Paragraphs
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text '  leer el texto
				'  Extraer detalles de formato
				If textRun.Style IsNot Nothing Then
					Dim fontSize = textRun.Style.FontSize '  tamaño de letra
					Dim isBold = textRun.Style.IsBold
					Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
				Else
					'  Imprimir texto sin detalles de formato
					Console.WriteLine($vbTab & "Text: {text}")
				End If
			Next paragraph
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

El código anterior lee el documento Word utilizando el método constructor de la clase WordDocument de la librería IronWord

Salida

Cómo leer un documento de Word con formato en C#: Figura 7 - Salida de consola del código anterior

Explicación

  1. Abra el documento de Word: Carga el documento de Word usando WordDocument de IronWord.
  2. Iterar a través de párrafos y ejecuciones: Utilice bucles anidados para iterar a través de párrafos y ejecuciones. Las tiradas representan porciones de texto con un formato específico.
  3. Extraer texto y formato: Extraer el contenido de texto de cada ejecución y comprobar las propiedades de formato. En este ejemplo, hemos demostrado cómo extraer el tamaño de fuente y el formato de negrita.
  4. Manejar excepciones: Se utiliza un bloque try-and-catch para manejar cualquier excepción e imprimirla.

    El archivo cargado se puede utilizar para imprimir documentos, también podemos cambiar el color de la fuente en el objeto de estilo.

Leer tablas de archivos Word

También podemos leer tablas de documentos Word. Añade el siguiente fragmento de código al programa.

using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar docx existente
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            //  Leer las tablas
            var tables = sampleDoc.Tables;
            foreach (var table in tables)
            {
                var rows = table.Rows;
                foreach (var row in rows)
                {
                    foreach (var cell in row.Cells)
                    {
                        var contents = cell.Contents;
                        contents.ForEach(x => Console.WriteLine(x)); 
                        //  imprimir contenido de celda
                    }                    
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar docx existente
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            //  Leer las tablas
            var tables = sampleDoc.Tables;
            foreach (var table in tables)
            {
                var rows = table.Rows;
                foreach (var row in rows)
                {
                    foreach (var cell in row.Cells)
                    {
                        var contents = cell.Contents;
                        contents.ForEach(x => Console.WriteLine(x)); 
                        //  imprimir contenido de celda
                    }                    
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
Imports IronWord
Friend Class Program
	Shared Sub Main()
		Try
			'  Cargar docx existente
			Dim sampleDoc = New WordDocument("sample.docx")
			Dim paragraphs = sampleDoc.Paragraphs
			'  Leer las tablas
			Dim tables = sampleDoc.Tables
			For Each table In tables
				Dim rows = table.Rows
				For Each row In rows
					For Each cell In row.Cells
						Dim contents = cell.Contents
						contents.ForEach(Sub(x) Console.WriteLine(x))
						'  imprimir contenido de celda
					Next cell
				Next row
			Next table
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

Aquí estamos utilizando el método get/set Tables en la clase WordDocument para obtener todas las tablas en el documento, luego iterar a través de ellas e imprimir el contenido.

Añadir estilo al texto existente

Podemos añadir nueva información de estilo a un documento Word existente utilizando la librería IronWord como se muestra en el siguiente fragmento de código.

using IronWord;
using IronWord.Models;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar docx existente
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; //  leer el texto
                //  Extraer detalles de formato
                if (textRun.Style != null)
                {
                    var fontSize = textRun.Style.FontSize; //  tamaño de letra
                    var isBold = textRun.Style.IsBold;
                    Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
                }
                else
                {
                    //  Imprimir texto sin detalles de formato
                    Console.WriteLine($"\tText: {text}");
                }
            }
            //Cambiar el formato del texto
            var style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), //  color azul
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].FirstTextRun.Style = style;
            sampleDoc.SaveAs("sample2.docx");            
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
using IronWord;
using IronWord.Models;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar docx existente
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; //  leer el texto
                //  Extraer detalles de formato
                if (textRun.Style != null)
                {
                    var fontSize = textRun.Style.FontSize; //  tamaño de letra
                    var isBold = textRun.Style.IsBold;
                    Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
                }
                else
                {
                    //  Imprimir texto sin detalles de formato
                    Console.WriteLine($"\tText: {text}");
                }
            }
            //Cambiar el formato del texto
            var style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), //  color azul
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].FirstTextRun.Style = style;
            sampleDoc.SaveAs("sample2.docx");            
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronWord
Imports IronWord.Models
Friend Class Program
	Shared Sub Main()
		Try
			'  Cargar docx existente
			Dim sampleDoc = New WordDocument("sample.docx")
			Dim paragraphs = sampleDoc.Paragraphs
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text '  leer el texto
				'  Extraer detalles de formato
				If textRun.Style IsNot Nothing Then
					Dim fontSize = textRun.Style.FontSize '  tamaño de letra
					Dim isBold = textRun.Style.IsBold
					Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
				Else
					'  Imprimir texto sin detalles de formato
					Console.WriteLine($vbTab & "Text: {text}")
				End If
			Next paragraph
			'Cambiar el formato del texto
			Dim style = New TextStyle() With {
				.FontFamily = "Caveat",
				.FontSize = 72,
				.TextColor = New IronColor(Color.Blue),
				.IsBold = True,
				.IsItalic = True,
				.IsUnderline = True,
				.IsSuperscript = False,
				.IsStrikethrough = True,
				.IsSubscript = False
			}
			paragraphs (1).FirstTextRun.Style = style
			sampleDoc.SaveAs("sample2.docx")
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

Aquí estamos creando un TextStyle y añadiéndolo al objeto párrafo existente

Añadir nuevo contenido con estilo al documento Word

Podemos añadir nuevo contenido a un documento de Word cargado como se muestra en el siguiente fragmento de código.

using IronWord;
using IronWord.Models;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar documento Word
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; //  leer el texto
                //  Extraer los detalles de formato
                if (textRun.Style != null)
                {
                    var fontSize = textRun.Style.FontSize; //  tamaño de letra
                    var isBold = textRun.Style.IsBold;
                    Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
                }
                else
                {
                    //  Imprimir texto sin detalles de formato
                    Console.WriteLine($"\tText: {text}");
                }
            }
            //  Añadir TextRun con Estilo al Párrafo
            TextRun blueTextRun = new TextRun();
            blueTextRun.Text = "Add text using IronWord";
            blueTextRun.Style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), //  color azul
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].AddTextRun(blueTextRun); 
            //  Añadir nuevo contenido al archivo Word y guardar
            Paragraph newParagraph = new Paragraph();
            TextRun newTextRun = new TextRun("New Add Information");
            newParagraph.AddTextRun(newTextRun);
            //  Configurar el texto
            TextRun introText = new TextRun("This is an example newParagraph with italic and bold styling.");
            TextStyle italicStyle = new TextStyle()
            {
                IsItalic = true
            };
            TextRun italicText = new TextRun("Italic example sentence.", italicStyle);
            TextStyle boldStyle = new TextStyle()
            {
                IsBold = true
            };
            TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
            //  Añadir el texto
            newParagraph.AddTextRun(introText);
            newParagraph.AddTextRun(italicText);
            newParagraph.AddTextRun(boldText);
            sampleDoc.SaveAs("sample2.docx");            
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
using IronWord;
using IronWord.Models;
class Program
{
    static void Main()
    {
        try
        {
            //  Cargar documento Word
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; //  leer el texto
                //  Extraer los detalles de formato
                if (textRun.Style != null)
                {
                    var fontSize = textRun.Style.FontSize; //  tamaño de letra
                    var isBold = textRun.Style.IsBold;
                    Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
                }
                else
                {
                    //  Imprimir texto sin detalles de formato
                    Console.WriteLine($"\tText: {text}");
                }
            }
            //  Añadir TextRun con Estilo al Párrafo
            TextRun blueTextRun = new TextRun();
            blueTextRun.Text = "Add text using IronWord";
            blueTextRun.Style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), //  color azul
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].AddTextRun(blueTextRun); 
            //  Añadir nuevo contenido al archivo Word y guardar
            Paragraph newParagraph = new Paragraph();
            TextRun newTextRun = new TextRun("New Add Information");
            newParagraph.AddTextRun(newTextRun);
            //  Configurar el texto
            TextRun introText = new TextRun("This is an example newParagraph with italic and bold styling.");
            TextStyle italicStyle = new TextStyle()
            {
                IsItalic = true
            };
            TextRun italicText = new TextRun("Italic example sentence.", italicStyle);
            TextStyle boldStyle = new TextStyle()
            {
                IsBold = true
            };
            TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
            //  Añadir el texto
            newParagraph.AddTextRun(introText);
            newParagraph.AddTextRun(italicText);
            newParagraph.AddTextRun(boldText);
            sampleDoc.SaveAs("sample2.docx");            
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronWord
Imports IronWord.Models
Friend Class Program
	Shared Sub Main()
		Try
			'  Cargar documento Word
			Dim sampleDoc = New WordDocument("sample.docx")
			Dim paragraphs = sampleDoc.Paragraphs
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text '  leer el texto
				'  Extraer los detalles de formato
				If textRun.Style IsNot Nothing Then
					Dim fontSize = textRun.Style.FontSize '  tamaño de letra
					Dim isBold = textRun.Style.IsBold
					Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
				Else
					'  Imprimir texto sin detalles de formato
					Console.WriteLine($vbTab & "Text: {text}")
				End If
			Next paragraph
			'  Añadir TextRun con Estilo al Párrafo
			Dim blueTextRun As New TextRun()
			blueTextRun.Text = "Add text using IronWord"
			blueTextRun.Style = New TextStyle() With {
				.FontFamily = "Caveat",
				.FontSize = 72,
				.TextColor = New IronColor(Color.Blue),
				.IsBold = True,
				.IsItalic = True,
				.IsUnderline = True,
				.IsSuperscript = False,
				.IsStrikethrough = True,
				.IsSubscript = False
			}
			paragraphs (1).AddTextRun(blueTextRun)
			'  Añadir nuevo contenido al archivo Word y guardar
			Dim newParagraph As New Paragraph()
			Dim newTextRun As New TextRun("New Add Information")
			newParagraph.AddTextRun(newTextRun)
			'  Configurar el texto
			Dim introText As New TextRun("This is an example newParagraph with italic and bold styling.")
			Dim italicStyle As New TextStyle() With {.IsItalic = True}
			Dim italicText As New TextRun("Italic example sentence.", italicStyle)
			Dim boldStyle As New TextStyle() With {.IsBold = True}
			Dim boldText As New TextRun("Bold example sentence.", boldStyle)
			'  Añadir el texto
			newParagraph.AddTextRun(introText)
			newParagraph.AddTextRun(italicText)
			newParagraph.AddTextRun(boldText)
			sampleDoc.SaveAs("sample2.docx")
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

Aquí estamos creando nuevos objetos TextRun y Paragraph con información de estilo y añadiéndolos al documento Word cargado.

Licencias (prueba gratuita disponible)

IronWord. Esta clave debe colocarse en appsettings.json.

{
    "IronWord.LicenseKey":"IRONWORD.MYLICENSE.KEY.TRIAL"
}

Proporcione su correo electrónico para obtener una licencia de prueba. Cuando envíe su dirección de correo electrónico, recibirá la clave por correo electrónico.

Cómo leer un documento de Word con formato en C#: Figura 8 - Formulario de prueba enviado correctamente

Conclusión

IronWord proporciona una forma cómoda de leer documentos de Word con formato en C#. Amplíe el código proporcionado en función de sus necesidades específicas y de la complejidad de los documentos con los que trabaje. Este tutorial sirve como punto de partida para integrar IronWord en sus aplicaciones C# para el tratamiento de documentos Word.

< ANTERIOR
Cómo crear documentos Word sin Office Interop en C#
SIGUIENTE >
3 Bibliotecas C# Word (Lista actualizada para desarrolladores)

¿Listo para empezar? Versión: 2024.7 recién publicada

Descarga gratuita de NuGet Descargas totales: 3,031 Ver licencias >
123