3 C# Word-Bibliotheken (Aktualisierte Liste für Entwickler)
Microsoft Word-Dokumente enthalten häufig umfangreiche Formatierungen wie Schriftarten, Stile und verschiedene Elemente, die sie optisch ansprechend machen. IronWord ist eine leistungsstarke Bibliothek von Iron Software, die über eine intuitive C#- und VB.NET-API für Word- und Docx-Dokumente verfügt. Es ist nicht erforderlich, Microsoft Office oder Word Interop zu installieren, um Word-Dokumente zu erstellen, zu bearbeiten und zu exportieren. IronWord unterstützt vollständig .NET 8, 7, 6, Framework, Core und Azure. Das bedeutet, dass die Bibliothek kein installiertes Word auf dem Rechner erfordert und die Dateien eigenständig liest. Wenn Sie mit C# arbeiten und Word-Dokumente lesen müssen, während deren Formatierung erhalten bleibt, wird Sie dieses Tutorial durch den Prozess mit der IronWord-Bibliothek führen.
Wie man (in C#) ein Word-Dokument mit Formatierung liest
- Installieren Sie die IronWord-Bibliothek, um Word-Dokumente zu lesen.
- Laden Sie 'sample.docx', das Eingabe-Word-Dokument, mithilfe der
WordDocument-Klasse aus der IronWord-Bibliothek. - Lesen Sie die Absätze mit Formatierung mithilfe eines geladenen Word-Dokuments.
- Zeigen Sie die extrahierten Daten mit Formatinformationen in der Konsolenausgabe an.
Voraussetzungen
- Visual Studio: Stellen Sie sicher, dass Visual Studio oder eine andere C#-Entwicklungsumgebung installiert ist.
- NuGet Package Manager: Stellen Sie sicher, dass Sie NuGet verwenden können, um Pakete in Ihrem Projekt zu verwalten.
Schritt 1: Erstellen Sie ein neues C#-Projekt
Erstellen Sie eine neue C#-Konsolenanwendung oder nutzen Sie ein bestehendes Projekt, in dem Sie Word-Dokumente lesen möchten.
Wählen Sie die Vorlage für Konsolenanwendungen und klicken Sie auf Weiter.

Klicken Sie auf die Schaltfläche 'Weiter', um den Lösungsnamen, den Projektnamen und den Pfad für den Code bereitzustellen.

Wählen Sie dann die gewünschte .NET-Version aus. Es ist immer am besten, die neueste verfügbare Version auszuwählen, obwohl Sie die erforderliche .NET-Version verwenden sollten, wenn Ihr Projekt spezifische Anforderungen hat.

Schritt 2: Installieren der IronWord-Bibliothek
Öffnen Sie Ihr C#-Projekt und installieren Sie die IronWord-Bibliothek über die NuGet-Paket-Manager-Konsole:
Das NuGet-Paket kann auch mit dem NuGet-Paket-Manager von Visual Studio installiert werden, wie unten gezeigt.

Schritt 3: Lesen des Word-Dokuments mit Formatierung
Um eine Word-Datei zu lesen, müssen wir zuerst ein neues Dokument erstellen und dann wie unten beschrieben Inhalte hinzufügen.

Speichern Sie nun die Datei im Projektverzeichnis und ändern Sie die Eigenschaften der Datei, um sie in das Ausgabeverzeichnis zu kopieren.

Fügen Sie nun das untenstehende Code-Snippet in die program.cs-Datei ein:
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 ClassDer obige Code liest das Word-Dokument mithilfe der IronWord-Bibliotheksklasse WordDocument-Konstruktormethode.
Ausgabe

Erklärung
- Öffnen Sie das Word-Dokument: Laden Sie das Word-Dokument mit
WordDocumentaus IronWord. - Absätze und Textabschnitte durchlaufen: Verwenden Sie verschachtelte Schleifen, um Absätze und Textabschnitte zu durchlaufen. Runs repräsentieren Textteile mit spezifischer Formatierung.
- Text und Formatierung extrahieren: Extrahieren Sie den Textinhalt aus jedem Durchlauf und überprüfen Sie die Formatierungseigenschaften. In diesem Beispiel haben wir gezeigt, wie man die Schriftgröße und fettgedruckte Formatierung extrahiert.
- Ausnahmebehandlung: Ein try-catch-Block dient dazu, alle Ausnahmen zu behandeln und auszugeben.
Die geladene Datei kann zum Drucken von Dokumenten verwendet werden, wir können auch die Schriftfarbe im Stilobjekt ändern.
Tabellen aus Word-Dateien lesen
Wir können auch Tabellen aus Word-Dokumenten lesen. Fügen Sie den untenstehenden Codeausschnitt zum Programm hinzu.
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 ClassHier verwenden wir die Tables-Eigenschaft auf der WordDocument-Klasse, um alle Tabellen im Dokument abzurufen, dann iterieren wir durch sie und drucken die Inhalte aus.
Stil zu vorhandenem Text hinzufügen
Wir können neuen Stilinformationen zu einem vorhandenen Word-Dokument mithilfe der IronWord-Bibliothek hinzufügen, wie im untenstehenden Codeausschnitt gezeigt.
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 ClassHier erstellen wir eine TextStyle und fügen sie dem vorhandenen Absatzobjekt hinzu.
Hinzufügen neuer gestylter Inhalte zum Word-Dokument
Wir können dem geladenen Word-Dokument wie im untenstehenden Codeausschnitt gezeigt neue Inhalte hinzufügen.
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 ClassHier erstellen wir neue TextRun und Paragraph Objekte mit Stilinformationen und fügen sie dem geladenen Word-Dokument hinzu.
Lizenzierung (Kostenlose Testversion verfügbar)
Erhalten Sie Ihren kostenlosen IronWord Testlizenz-Schlüssel. Dieser Schlüssel muss in appsettings.json platziert werden.
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}
Geben Sie Ihre E-Mail für eine Testlizenz an. Nach der Eingabe Ihrer E-Mail-Adresse wird der Schlüssel per E-Mail zugestellt.

Abschluss
IronWord bietet eine bequeme Möglichkeit, Word-Dokumente mit Formatierung in C# zu lesen. Erweitern Sie den bereitgestellten Code basierend auf Ihren spezifischen Anforderungen und der Komplexität der Dokumente, mit denen Sie arbeiten. Dieses Tutorial dient als Ausgangspunkt für die Integration von IronWord in Ihre C#-Anwendungen zur Verarbeitung von Word-Dokumenten.

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.
Verwandte Artikel

