using IronWord;
using IronWord.Models;
// Load docx
WordDocument doc = new WordDocument("document.docx");
// Add text
doc.AddText("Add text using IronWord");
// Export docx
doc.SaveAs("save_document.docx");
Comment lire un document Word avec formatage en C#
Jordi Bardia
février 22, 2024
Partager:
Les documents Microsoft Word contiennent souvent un formatage riche tel que des polices, des styles et divers éléments qui les rendent visuellement attrayants. IronWord est une puissante bibliothèque deIron Software qui dispose d'une API intuitive pour les documents Word et Docx en C# et VB.NET. Il n'est pas nécessaire d'installer Microsoft Office ou Word Interop pour créer, modifier et exporter des documents Word. IronWord est entièrement compatible avec .NET 8, 7, 6, Framework, Core et Azure. Cela signifie que la bibliothèque ne nécessite pas que Word soit installé sur la machine et qu'elle lit les fichiers de manière indépendante. Si vous travaillez avec C# et que vous avez besoin de lire des documents Word tout en préservant leur formatage, ce tutoriel vous guidera tout au long du processus à l'aide de la fonctionIronWord bibliothèque.
Comment (en C# ;) lire un document Word avec formatage
Installer la bibliothèque IronWord pour lire les documents Word.
Chargez 'sample.docx', le document Word d'entrée en utilisant la classe WordDocument de la bibliothèque IronWord.
Lisez les paragraphes avec formatage en utilisant un document Word chargé.
Afficher les données extraites avec les informations de format dans la sortie de la console.
Conditions préalables
Visual Studio: Assurez-vous que Visual Studio ou tout autre environnement de développement C# est installé.
NuGet Package Manager: Assurez-vous que vous pouvez utiliser NuGet pour gérer les paquets dans votre projet
Étape 1 : Créer un nouveau projet C
Créez une nouvelle application console C# ou utilisez un projet existant dans lequel vous souhaitez lire des documents Word.
Sélectionnez le modèle d'application de la console et cliquez sur suivant.
Cliquez sur le bouton "Suivant" pour indiquer le nom de la solution, le nom du projet et le chemin d'accès au code.
Sélectionnez ensuite la version .NET souhaitée. La meilleure pratique consiste toujours à choisir la dernière version disponible, mais si votre projet a des exigences spécifiques, utilisez la version .NET nécessaire.
Étape 2 : Installation de la bibliothèque IronWord
Ouvrez votre projet C# et installez la bibliothèque IronWord à l'aide de la console du gestionnaire de paquets NuGet :
Install-Package IronWord
Le paquet NuGet peut également être installé à l'aide du gestionnaire de paquets NuGet de Visual Studio, comme indiqué ci-dessous.
Étape 3 : Lire le document Word avec formatage
Pour lire un fichier Word, nous devons tout d'abord créer un nouveau document et y ajouter du contenu, comme indiqué ci-dessous.
Enregistrez maintenant le fichier dans le répertoire du projet et modifiez les propriétés du fichier pour le copier dans le répertoire de sortie
Ajoutez maintenant l'extrait de code suivant au fichier program.cs
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // read the text
// Extract Formatting details
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;
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // read the text
// Extract Formatting details
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
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' read the text
' Extract Formatting details
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 Class
Le code ci-dessus lit le document Word en utilisant la méthode du constructeur de la classe WordDocument de la bibliothèque IronWord
Sortie
Explication
Ouvrir le document Word : Chargez le document Word en utilisant WordDocument d'IronWord.
Itérer à travers les paragraphes et les séries : Utilisez des boucles imbriquées pour parcourir les paragraphes et les séries. Les séries représentent des portions de texte avec une mise en forme spécifique.
Extraire le texte et le formatage : Extraire le contenu textuel de chaque exécution et vérifier les propriétés de formatage. Dans cet exemple, nous avons montré comment extraire la taille de la police et le formatage en gras.
Gérer les exceptions : Un bloc "try-and-catch" est utilisé pour gérer les exceptions et les imprimer.
Le fichier chargé peut être utilisé pour imprimer des documents, nous pouvons également modifier la couleur de la police dans l'objet style.
Lire des tableaux à partir de fichiers Word
Nous pouvons également lire des tableaux à partir de documents Word. Ajoutez l'extrait de code ci-dessous au programme.
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// 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");
var paragraphs = sampleDoc.Paragraphs;
// 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")
Dim paragraphs = sampleDoc.Paragraphs
' 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 Class
Ici, nous utilisons la méthode get/set Tables de la classe WordDocument pour récupérer toutes les tables du document, les parcourir et en imprimer le contenu.
Ajouter un style à un texte existant
Nous pouvons ajouter de nouvelles informations de style à un document Word existant à l'aide de la bibliothèque IronWord, comme le montre l'extrait de code ci-dessous.
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // read the text
// Extract Formatting details
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 formating of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(Color.Blue), // blue color
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
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // read the text
// Extract Formatting details
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 formating of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(Color.Blue), // blue color
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
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' read the text
' Extract Formatting details
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 formating of the text
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
Ici, nous créons un TextStyle et l'ajoutons à l'objet paragraphe existant
Ajout d'un nouveau contenu stylé au document Word
Nous pouvons ajouter un nouveau contenu à un document Word chargé, comme le montre l'extrait de code ci-dessous.
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // read the text
// Extract the formatting details
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(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
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);
// Add the text
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
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // read the text
// Extract the formatting details
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(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
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);
// Add the text
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
' Load Word Document
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' read the text
' Extract the formatting details
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(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
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)
' Add the text
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
Ici, nous créons de nouveaux objets TextRun et Paragraphe avec des informations de style et nous les ajoutons au document Word chargé.
Licence (essai gratuit disponible)
IronWord. Cette clé doit être placée dans appsettings.json.
Indiquez votre adresse électronique pour obtenir une licence d'essai. Une fois que vous avez indiqué votre adresse électronique, la clé vous sera envoyée par courrier électronique.
Conclusion
IronWord offre un moyen pratique de lire des documents Word avec formatage en C#. Étendez le code fourni en fonction de vos besoins spécifiques et de la complexité des documents avec lesquels vous travaillez. Ce tutoriel sert de point de départ à l'intégration de l'applicationIronWord dans vos applications C# pour le traitement des documents Word.
Jordi maîtrise parfaitement Python, C# et C++. Lorsqu'il ne met pas à profit ses compétences chez Iron Software, il se consacre à la programmation de jeux. Partageant des responsabilités en matière de tests de produits, de développement de produits et de recherche, Jordi apporte une valeur ajoutée considérable à l'amélioration continue des produits. Cette expérience variée le stimule et l'engage, et il dit que c'est l'un des aspects qu'il préfère dans son travail chez Iron Software. Jordi a grandi à Miami, en Floride, et a étudié l'informatique et les statistiques à l'université de Floride.
< PRÉCÉDENT Comment créer des documents Word sans l'interopérabilité d'Office en C#
SUIVANT > 3 Bibliothèques Word C# (Liste mise à jour pour les développeurs)
Des millions d'ingénieurs dans le monde entier lui font confiance
Réservez une démo en direct gratuite
Réservez une démonstration personnelle de 30 minutes.
Pas de contrat, pas de détails de carte, pas d'engagements.
Voici ce à quoi vous pouvez vous attendre :
Une démonstration en direct de notre produit et de ses principales fonctionnalités
Obtenez des recommandations de fonctionnalités spécifiques au projet
Toutes vos questions trouvent réponse pour vous assurer de disposer de toutes les informations dont vous avez besoin. (Aucun engagement de votre part.)
CHOISIR L'HEURE
VOS INFORMATIONS
Réservez votre démo en direct gratuite
Fiable par plus de 2 millions d'ingénieurs dans le monde entier