IRONWORD VERWENDEN

Wie man ein Word-Dokument mit Formatierung in C# liest

Chaknith Bin
Chaknith Bin
22. Februar 2024
Teilen Sie:

Microsoft Word-Dokumente enthalten oft umfangreiche Formatierungen wie Schriftarten, Formate und verschiedene Elemente, die sie optisch ansprechend machen. IronWord ist eine leistungsstarke Bibliothek von Iron Software, die über eine intuitive C# und VB.NET Word und Docx Document API verfügt. Um Word-Dokumente zu erstellen, zu bearbeiten und zu exportieren, müssen Sie weder Microsoft Office noch Word Interop installieren. IronWord unterstützt vollständig .NET 8, 7, 6, Framework, Core und Azure. Dies bedeutet, dass die Bibliothek kein auf dem Rechner installiertes Word benötigt und die Dateien unabhängig liest. Wenn Sie mit C# arbeiten und Word-Dokumente lesen müssen, während Sie deren Formatierung beibehalten, führt Sie dieses Tutorial durch den Prozess mit der IronWord-Bibliothek.

Wie man (in C#;) Word-Dokument mit Formatierung lesen

  1. Installieren Sie die IronWord-Bibliothek, um Word-Dokumente zu lesen.

  2. Verwenden Sie die WordDocument-Klasse aus der IronWord-Bibliothek, um 'sample.docx', das Eingabe-Word-Dokument, zu laden.

  3. Lesen Sie die Absätze mit Formatierung in einem geladenen Word-Dokument.

  4. Zeigt die extrahierten Daten mit Formatinformationen in der Konsolenausgabe an.

Voraussetzungen

  1. Visual Studio: Stellen Sie sicher, dass Visual Studio oder eine andere C#-Entwicklungsumgebung installiert ist.

  2. NuGet-Paket-Manager: Stellen Sie sicher, dass Sie NuGet verwenden können, um Pakete in Ihrem Projekt zu verwalten.

Schritt 1: Erstellen eines neuen C# Projekts

Erstellen Sie eine neue C#-Konsolenanwendung oder verwenden Sie ein vorhandenes Projekt, in dem Sie Word-Dokumente lesen möchten.

Wählen Sie die Konsolenanwendungsvorlage aus und klicken Sie auf Weiter.

So lesen Sie ein Word-Dokument mit Formatierung in C#: Abbildung 1 - Erstellen eines neuen C#-Projekts

Klicken Sie auf die Schaltfläche "Weiter", um den Namen der Lösung, den Projektnamen und den Pfad für den Code anzugeben.

Wie man ein Word-Dokument mit Formatierung in C# liest: Abbildung 2 - Das neue Projekt konfigurieren

Wählen Sie dann die gewünschte .NET-Version aus. Am besten wählen Sie immer die aktuellste verfügbare Version. Wenn Ihr Projekt jedoch besondere Anforderungen stellt, sollten Sie die erforderliche .NET-Version verwenden.

Wie man ein Word-Dokument mit Formatierung in C# liest: Abbildung 3 - Auswahl des erforderlichen .NET-Versionstyps

Schritt 2: Installieren Sie die IronWord-Bibliothek

Öffnen Sie Ihr C#-Projekt und installieren Sie die IronWord-Bibliothek über die NuGet-Paketmanager-Konsole:

Install-Package IronWord

Das NuGet-Paket kann auch mit dem NuGet-Paketmanager von Visual Studio installiert werden, wie unten gezeigt.

Wie man ein Word-Dokument mit Formatierung in C# liest: Abbildung 4 - Installation von IronWord über den NuGet-Paket-Manager

Schritt 3: Lesen des Word-Dokuments mit Formatierung

Um eine Word-Datei zu lesen, müssen wir zunächst ein neues Dokument erstellen und ihm dann einige Inhalte hinzufügen (siehe unten).

Wie man ein Word-Dokument mit Formatierung in C# liest: Abbildung 5 - Erstelltes Beispieldokument

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

Wie man Word-Dokumente mit Formatierung in C# liest: Abbildung 6 - So sollten die Dateieigenschaften aussehen

Fügen Sie nun den folgenden Codeschnipsel in die Datei program.cs ein

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
$vbLabelText   $csharpLabel

Der obige Code liest das Word-Dokument mithilfe der IronWord-Bibliotheksklasse WordDocument-Konstruktormethode.

Ausgabe

Wie man ein Word-Dokument mit Formatierung in C# liest: Abbildung 7 - Konsolenausgabe aus dem vorherigen Code

Erläuterung

  1. Öffnen Sie das Word-Dokument: Laden Sie das Word-Dokument mit WordDocument von IronWord.

  2. Durch Absätze und Durchläufe iterieren: Verwenden Sie verschachtelte Schleifen, um durch Absätze und Durchläufe zu iterieren. Läufe stellen Textabschnitte mit bestimmten Formatierungen dar.

  3. 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 die fette Formatierung extrahiert.

  4. Ausnahmen behandeln: Ein Try-Catch-Block wird verwendet, um Ausnahmen zu behandeln und sie auszugeben.

    Die geladene Datei kann zum Drucken von Dokumenten verwendet werden, und 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 nachstehenden Codeausschnitt in das Programm ein.

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
$vbLabelText   $csharpLabel

Hier verwenden wir die get/set-Methode Tables in der WordDocument-Klasse, um alle Tabellen im Dokument abzurufen, dann iterieren wir durch sie und drucken den Inhalt aus.

Stil zu vorhandenem Text hinzufügen

Mit der IronWord-Bibliothek können wir einem bestehenden Word-Dokument neue Formatvorlagen hinzufügen, wie im folgenden 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;
            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
$vbLabelText   $csharpLabel

Hier erstellen wir einen TextStyle und fügen ihn dem bestehenden Absatzobjekt hinzu

Hinzufügen neuer gestalteter Inhalte zum Word-Dokument

Wir können neue Inhalte zu einem geladenen Word-Dokument hinzufügen, wie im folgenden Codeausschnitt gezeigt.

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
$vbLabelText   $csharpLabel

Hier erstellen wir neue TextRun- und Paragraph-Objekte mit Stilinformationen und fügen sie dem geladenen Word-Dokument hinzu.

Lizenzierung (kostenlose Testversion verfügbar)

IronWord. Dieser Schlüssel muss in appsettings.json platziert werden.

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

Geben Sie Ihre E-Mail-Adresse an, um eine Testlizenz zu erhalten. Nachdem Sie Ihre E-Mail-ID angegeben haben, wird der Schlüssel per E-Mail zugestellt.

Wie man ein Word-Dokument mit Formatierung in C# liest: Abbildung 8 - Erfolgreich eingereichtes Testformular

Schlussfolgerung

IronWord bietet eine bequeme Möglichkeit, Word-Dokumente mit Formatierung in C# zu lesen. Erweitern Sie den mitgelieferten Code je nach 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.

Chaknith Bin
Software-Ingenieur
Chaknith arbeitet an IronXL und IronBarcode. Er hat tiefgehende Expertise in C# und .NET und hilft, die Software zu verbessern und Kunden zu unterstützen. Seine Erkenntnisse aus Benutzerinteraktionen tragen zu besseren Produkten, Dokumentation und einem insgesamt besseren Erlebnis bei.
< PREVIOUS
Erstellen von Word-Dokumenten ohne Office-Interop in C#
NÄCHSTES >
3 C# Word-Bibliotheken (Aktualisierte Liste für Entwickler)

Sind Sie bereit, loszulegen? Version: 2025.4 gerade veröffentlicht

Lizenzen anzeigen >