Pruebas en un entorno real
Pruebe en producción sin marcas de agua.
Funciona donde lo necesites.
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.
WordDocument
de la librería IronWord.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.
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.
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.
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.
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.
Ahora guarda el archivo en el directorio del proyecto y cambia las propiedades del archivo para copiarlo en el directorio de salida
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
El código anterior lee el documento Word utilizando el método constructor de la clase WordDocument
de la librería IronWord
WordDocument
de IronWord.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.
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
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.
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
Aquí estamos creando un TextStyle
y añadiéndolo al objeto párrafo existente
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
Aquí estamos creando nuevos objetos TextRun
y Paragraph con información de estilo y añadiéndolos al documento Word cargado.
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.
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.
9 productos API .NET para sus documentos de oficina