Cómo Leer Documento Word Con Formateo en C#
Los documentos de Microsoft Word suelen contener un formato rico como fuentes, estilos y varios elementos que los hacen visualmente atractivos. IronWord es una potente biblioteca de Iron Software que tiene una API intuitiva de C# y VB.NET para Documentos Word y Docx. No hay necesidad de instalar Microsoft Office o Word Interop para construir, editar y exportar documentos Word. IronWord soporta completamente .NET 8, 7, 6, Framework, Core y Azure. Esto significa que la biblioteca no requiere Word instalado en la máquina y lee los archivos de forma independiente. Si estás trabajando con C# y necesitas leer documentos Word mientras preservas su formato, este tutorial te guiará a través del proceso usando la biblioteca IronWord.
Cómo leer un documento de Word con formato (en C#)
- Instala la biblioteca IronWord para leer documentos Word.
- Carga 'sample.docx', el documento Word de entrada utilizando la clase
WordDocumentde la biblioteca IronWord. - Lee los párrafos con formato usando un documento Word cargado.
- Muestra los datos extraídos con información de formato en la salida de la consola.
Requisitos previos
- Visual Studio: Asegúrate de tener instalado Visual Studio o cualquier otro entorno de desarrollo de C#.
- Administrador de Paquetes NuGet: Asegúrate de poder usar NuGet para gestionar paquetes en tu proyecto.
Paso 1: Crear un nuevo proyecto de C
Crea una nueva aplicación de consola C# o usa un proyecto existente donde quieras leer documentos Word.
Selecciona la plantilla de aplicación de consola y haz clic en siguiente.

Haz clic en el botón 'Siguiente' para proporcionar el nombre de la solución, el nombre del proyecto y la ruta para el código.

Luego selecciona la versión deseada de .NET. La mejor práctica es siempre seleccionar la última versión disponible, aunque si tu proyecto tiene requisitos específicos entonces usa la versión de .NET necesaria.

Paso 2: Instalar la biblioteca de IronWord
Abre tu proyecto C# e instala la biblioteca IronWord usando la Consola del Administrador de Paquetes NuGet:
Install-Package IronWord
El paquete NuGet también se puede instalar usando el Administrador de Paquetes de NuGet de Visual Studio, como se muestra abajo.

Paso 3: Leer el documento de Word con formato
Para leer un archivo Word, primero, necesitamos crear un nuevo documento y luego agregarle algo de contenido como se muestra a continuación.

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

Ahora añade el siguiente fragmento de código al archivo program.cs:
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through each paragraph in the Word document
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through each paragraph in the Word document
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
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
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through each paragraph in the Word document
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract Formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
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 ClassEl código anterior lee el documento Word usando el método constructor de la clase WordDocument de la biblioteca IronWord.
Resultado

Explicación
- Abre el Documento Word: Carga el documento Word usando
WordDocumentde IronWord. - Iterar a Través de Párrafos y Ejecutar: Usa bucles anidados para iterar a través de párrafos y ejecuciones. Las ejecuciones representan porciones de texto con un formato específico.
- Extraer Texto y Formato: Extrae contenido de texto de cada ejecución y verifica las propiedades de formato. En este ejemplo, hemos demostrado cómo extraer el tamaño de la fuente y el formato en negrita.
- Manejar Excepciones: Se utiliza un bloque try-and-catch para manejar cualquier excepción e imprimirlas.
El archivo cargado se puede usar para imprimir documentos, también podemos cambiar el color de la fuente en el objeto de estilo.
Leer tablas de archivos de Word
También podemos leer tablas de documentos Word. Agrega el siguiente fragmento de código al programa.
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
// Read Tables
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));
// Print cell contents
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
// Read Tables
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));
// Print cell contents
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}Imports IronWord
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
' Read Tables
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))
' Print cell contents
Next cell
Next row
Next table
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End ClassAquí estamos usando la propiedad Tables en la clase WordDocument para obtener todas las tablas en el documento, luego iterar a través de ellas e imprimir el contenido.
Agregar estilo al texto existente
Podemos agregar nueva información de estilo a un documento Word existente usando la biblioteca IronWord como se muestra en el siguiente fragmento de código.
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Change the formatting of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].FirstTextRun.Style = style;
// Save the document with the new style applied
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
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Change the formatting of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].FirstTextRun.Style = style;
// Save the document with the new style applied
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
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract Formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
' Change the formatting of the text
Dim style = New TextStyle() With {
.FontFamily = "Caveat",
.FontSize = 72,
.TextColor = New IronColor(System.Drawing.Color.Blue),
.IsBold = True,
.IsItalic = True,
.IsUnderline = True,
.IsSuperscript = False,
.IsStrikethrough = True,
.IsSubscript = False
}
paragraphs(1).FirstTextRun.Style = style
' Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End ClassAquí estamos creando un TextStyle y agregándolo al objeto de párrafo existente.
Agregar contenido nuevo con estilo al documento de Word
Podemos agregar nuevo contenido a un documento Word cargado como se muestra en el siguiente fragmento de código.
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract the formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Add TextRun with Style to Paragraph
TextRun blueTextRun = new TextRun();
blueTextRun.Text = "Add text using IronWord";
blueTextRun.Style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].AddTextRun(blueTextRun);
// Add New Content to the Word file and save
Paragraph newParagraph = new Paragraph();
TextRun newTextRun = new TextRun("New Add Information");
newParagraph.AddTextRun(newTextRun);
// Configure the text with different styles
TextRun introText = new TextRun("This is an example paragraph 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);
// Add the styled text to the paragraph
newParagraph.AddTextRun(introText);
newParagraph.AddTextRun(italicText);
newParagraph.AddTextRun(boldText);
// Save the modified document
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
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract the formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Add TextRun with Style to Paragraph
TextRun blueTextRun = new TextRun();
blueTextRun.Text = "Add text using IronWord";
blueTextRun.Style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].AddTextRun(blueTextRun);
// Add New Content to the Word file and save
Paragraph newParagraph = new Paragraph();
TextRun newTextRun = new TextRun("New Add Information");
newParagraph.AddTextRun(newTextRun);
// Configure the text with different styles
TextRun introText = new TextRun("This is an example paragraph 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);
// Add the styled text to the paragraph
newParagraph.AddTextRun(introText);
newParagraph.AddTextRun(italicText);
newParagraph.AddTextRun(boldText);
// Save the modified document
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
' Load Word Document
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract the formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
' Add TextRun with Style to Paragraph
Dim blueTextRun As New TextRun()
blueTextRun.Text = "Add text using IronWord"
blueTextRun.Style = New TextStyle() With {
.FontFamily = "Caveat",
.FontSize = 72,
.TextColor = New IronColor(System.Drawing.Color.Blue),
.IsBold = True,
.IsItalic = True,
.IsUnderline = True,
.IsSuperscript = False,
.IsStrikethrough = True,
.IsSubscript = False
}
paragraphs(1).AddTextRun(blueTextRun)
' Add New Content to the Word file and save
Dim newParagraph As New Paragraph()
Dim newTextRun As New TextRun("New Add Information")
newParagraph.AddTextRun(newTextRun)
' Configure the text with different styles
Dim introText As New TextRun("This is an example paragraph 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)
' Add the styled text to the paragraph
newParagraph.AddTextRun(introText)
newParagraph.AddTextRun(italicText)
newParagraph.AddTextRun(boldText)
' Save the modified document
sampleDoc.SaveAs("sample2.docx")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End ClassAquí estamos creando nuevos objetos TextRun y Paragraph con información de estilo y agregándolos al documento Word cargado.
Licencia (Prueba gratuita disponible)
Obtén tu clave de licencia de prueba gratuita de IronWord. Esta clave necesita ser ubicada en appsettings.json.
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}Proporcione su correo para una licencia de prueba. Después de enviar su ID de correo electrónico, la clave se entregará por correo.

Conclusión
IronWord ofrece una manera conveniente de leer documentos Word con formato en C#. Extiende el código proporcionado según tus requisitos específicos y la complejidad de los documentos con los que estás trabajando. Este tutorial sirve como punto de partida para integrar IronWord en tus aplicaciones C# para el procesamiento de documentos Word.
Preguntas Frecuentes
¿Cómo puedo leer documentos de Word con formato en C#?
Para leer documentos de Word con formato en C#, utiliza la biblioteca IronWord. Comienza instalando IronWord a través del Administrador de paquetes NuGet. Carga el documento utilizando la clase WordDocument e itera a través de los párrafos para extraer texto y detalles de formato.
¿Cuáles son los pasos para configurar un proyecto C# para leer documentos de Word?
Para configurar un proyecto C# para leer documentos de Word, instala Visual Studio u otro entorno de desarrollo C#. Usa el Administrador de paquetes NuGet para agregar IronWord a tu proyecto. Carga documentos de Word con la clase WordDocument para acceder a su contenido.
¿Cómo manejo excepciones al leer documentos de Word en C#?
Al leer documentos de Word en C# utilizando IronWord, maneja excepciones implementando bloques try-catch alrededor de tu código de procesamiento de documentos. Esto ayudará a manejar errores de ejecución y asegurará un comportamiento robusto de la aplicación.
¿Puedo leer tablas de documentos de Word usando C#?
Sí, puedes leer tablas de documentos de Word usando IronWord en C#. Accede a las tablas a través de la propiedad Tables de la clase WordDocument e itera a través de los datos de la tabla según sea necesario.
¿Cómo puedo modificar estilos de texto en un documento de Word usando C#?
Modifica estilos de texto en un documento de Word usando IronWord creando un objeto TextStyle y aplicándolo a ejecuciones de texto o párrafos específicos. Esto te permite personalizar fuentes, tamaños y otros atributos de estilo.
¿Es posible agregar nuevo contenido a documentos de Word en C#?
Sí, puedes agregar nuevo contenido a documentos de Word usando IronWord en C#. Crea objetos TextRun y Paragraph para agregar contenido con estilo al documento antes de guardar tus cambios.
¿Cómo guardo modificaciones a un documento de Word en C#?
Después de editar un documento de Word utilizando IronWord, guarda tus cambios llamando al método Save en la instancia WordDocument. Especifica la ruta del archivo para crear un nuevo documento con las modificaciones aplicadas.
¿Necesito tener instalado Microsoft Office para procesar documentos de Word en C#?
No, no necesitas tener instalado Microsoft Office para procesar documentos de Word en C# utilizando IronWord. La biblioteca funciona de manera independiente de Microsoft Office, permitiéndote trabajar con archivos de Word directamente.
¿Qué versiones de .NET son compatibles con una biblioteca de procesamiento de Word?
IronWord es compatible con una amplia gama de versiones de .NET, incluyendo .NET 8, 7, 6, Framework, Core y Azure. Esto asegura que cumpla con varios requisitos de proyectos y entornos.
¿Cómo puedo obtener una licencia de prueba para una biblioteca de procesamiento de Word en C#?
Para obtener una licencia de prueba para IronWord, visita el sitio web de Iron Software y proporciona tu dirección de correo electrónico. Recibirás una clave de licencia de prueba por correo electrónico, que puedes agregar a tu archivo appsettings.json.








