Jak odczytac dokument Word z formatowaniem w C#
Dokumenty WORD często zawierają bogate formatowanie, takie jak czcionki, style i różne elementy, które sprawiają, że są one atrakcyjne wizualnie. IronWord to potężna biblioteka firmy Iron Software, która posiada intuicyjny interfejs API do obsługi dokumentów Word i Docx w językach C# i VB.NET. Nie ma potrzeby instalowania pakietu Microsoft Office ani Word Interop w celu tworzenia, edytowania i eksportowania dokumentów Word. IronWord w pełni obsługuje .NET 8, 7, 6, Framework, Core oraz Azure. Oznacza to, że biblioteka nie wymaga zainstalowania programu WORD na komputerze i odczytuje pliki samodzielnie. Jeśli pracujesz w języku C# i chcesz odczytywać dokumenty Worda z zachowaniem ich formatowania, ten samouczek przeprowadzi Cię przez proces korzystania z biblioteki IronWord.
Jak (w języku C#) odczytać dokument Worda z zachowaniem formatowania
- Zainstaluj bibliotekę IronWord, aby odczytywać dokumenty Word.
- Załaduj plik "sample.docx", czyli dokument Worda, używając klasy
WordDocumentz biblioteki IronWord. - Przeczytaj akapity z formatowaniem, korzystając z załadowanego dokumentu WORD.
- Wyświetl wyodrębnione dane wraz z informacjami o formacie w wyjściu konsoli.
Wymagania wstępne
- Visual Studio: Upewnij się, że masz zainstalowane Visual Studio lub inne środowisko programistyczne C#.
- Menedżer pakietów NuGet: Upewnij się, że możesz używać NuGet do zarządzania pakietami w swoim projekcie
Krok 1: Utwórz nowy projekt w języku C
Utwórz nową aplikację konsolową w języku C# lub skorzystaj z istniejącego projektu, w którym chcesz odczytywać dokumenty WORD.
Wybierz szablon aplikacji konsolowej i kliknij Dalej.

Kliknij przycisk "Dalej", aby podać nazwę rozwiązania, nazwę projektu i ścieżkę do kodu.

Następnie wybierz żądaną wersję .NET. Najlepszą praktyką jest zawsze wybieranie najnowszej dostępnej wersji, jednak jeśli projekt ma specyficzne wymagania, należy użyć odpowiedniej Wersji .NET.

Krok 2: Zainstaluj bibliotekę IronWord
Otwórz projekt C# i zainstaluj bibliotekę IronWord za pomocą konsoli NuGet Package Manager Console:
Install-Package IronWord
Pakiet NuGet można również zainstalować za pomocą menedżera pakietów NuGet w programie Visual Studio, jak pokazano poniżej.

Krok 3: Przeczytaj dokument WORD z formatowaniem
Aby odczytać plik WORD, najpierw musimy utworzyć nowy dokument, a następnie dodać do niego treść, jak poniżej.

Teraz zapisz plik w katalogu projektu i zmień jego właściwości, aby skopiować go do katalogu wyjściowego.

Teraz dodaj poniższy fragment kodu do pliku 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 Class
Powyższy kod odczytuje dokument Worda przy użyciu metody konstruktora klasy biblioteki IronWord WordDocument.
Wynik

Wyjaśnienie
- Otwórz dokument WORD: Załaduj dokument WORD za pomocą
WordDocumentz IronWord. - Przeglądaj akapity i sekcje: Używaj pętli zagnieżdżonych do przeglądania akapitów i sekcji. Wiersze oznaczają fragmenty tekstu o określonym formatowaniu.
- Wyodrębnij tekst i formatowanie: Wyodrębnij treść tekstową z każdego przebiegu i sprawdź właściwości formatowania. W tym przykładzie pokazaliśmy, jak wyodrębnić rozmiar czcionki i formatowanie pogrubione.
- Obsługa wyjątków: Blok try-and-catch służy do obsługi wszelkich wyjątków i ich wyświetlania za pomocą funkcji PRINT.
Załadowany plik można wykorzystać do drukowania dokumentów, możemy również zmienić kolor czcionki w obiekcie stylu.
Odczytywanie tabel z plików WORD
Możemy również odczytywać tabele z dokumentów WORD. Dodaj poniższy fragment kodu do programu.
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 Class
W tym przypadku używamy właściwości Tables w klasie WordDocument, aby pobrać wszystkie tabele w dokumencie, a następnie iterować przez nie i wydrukować zawartość.
Dodaj styl do istniejącego tekstu
Możemy dodać nowe informacje o stylu do istniejącego dokumentu WORDa, korzystając z biblioteki IronWord, jak pokazano w poniższym fragmencie kodu.
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 Class
Tutaj tworzymy TextStyle i dodajemy go do istniejącego obiektu akapitu.
Dodawanie nowej treści sformatowanej do dokumentu WORD
Możemy dodawać nową treść do załadowanego dokumentu WORDa, jak pokazano w poniższym fragmencie kodu.
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 Class
W tym miejscu tworzymy nowe obiekty TextRun i Paragraph z informacjami o stylu i dodajemy je do załadowanego dokumentu WORD.
Licencjonowanie (dostępna bezpłatna wersja próbna)
Zdobądź bezpłatną licencję próbną IronWord. Ten klucz należy umieścić w appsettings.json.
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}
Podaj swój adres e-mail, aby otrzymać Licencję Trial. Po podaniu adresu e-mail klucz zostanie dostarczony pocztą elektroniczną.

Wnioski
IronWord zapewnia wygodny sposób odczytu dokumentów Word z zachowaniem formatowania w języku C#. Rozszerz dostarczony kod w oparciu o swoje konkretne wymagania i złożoność dokumentów, nad którymi pracujesz. Ten samouczek służy jako punkt wyjścia do integracji IronWord z aplikacjami C# w celu przetwarzania dokumentów WORD.
Często Zadawane Pytania
Jak mogę odczytać dokumenty WORDa z formatowaniem w języku C#?
Aby odczytać dokumenty Worda z formatowaniem w języku C#, użyj biblioteki IronWord. Zacznij od zainstalowania IronWord za pomocą menedżera pakietów NuGet. Załaduj dokument za pomocą klasy WordDocument i przejdź przez akapity, aby wyodrębnić tekst i szczegóły formatowania.
Jakie kroki należy wykonać, aby skonfigurować projekt C# do odczytu dokumentów WORD?
Aby skonfigurować projekt C# do odczytu dokumentów Word, zainstaluj Visual Studio lub inne środowisko programistyczne C#. Użyj menedżera pakietów NuGet, aby dodać IronWord do swojego projektu. Załaduj dokumenty Word za pomocą klasy WordDocument, aby uzyskać dostęp do ich zawartości.
Jak radzić sobie z wyjątkami podczas odczytywania dokumentów WORDa w języku C#?
Podczas odczytywania dokumentów WORD w języku C# przy użyciu IronWord należy obsługiwać wyjątki poprzez implementację bloków try-catch wokół kodu przetwarzającego dokument. Pomoże to w zarządzaniu błędami wykonania i zapewni stabilne działanie aplikacji.
Czy mogę odczytywać tabele z dokumentów WORDa przy użyciu języka C#?
Tak, można odczytywać tabele z dokumentów Worda za pomocą IronWord w języku C#. Dostęp do tabel uzyskuje się poprzez właściwość Tables klasy WordDocument, a dane tabeli można przeglądać w razie potrzeby.
Jak mogę modyfikować style tekstu w dokumencie WORDa za pomocą języka C#?
Modyfikuj style tekstu w dokumencie WORD za pomocą IronWord, tworząc obiekt TextStyle i stosując go do określonych fragmentów tekstu lub akapitów. Pozwala to dostosować czcionki, rozmiary i inne atrybuty stylów.
Czy w języku C# można dodawać nowe treści do dokumentów WORD?
Tak, można dodawać nową treść do dokumentów Worda za pomocą IronWord w języku C#. Należy utworzyć obiekty TextRun i Paragraph, aby dodać sformatowaną treść do dokumentu przed zapisaniem zmian.
Jak zapisać zmiany w dokumencie WORD w języku C#?
Po edycji dokumentu WORD za pomocą IronWord zapisz zmiany, wywołując metodę Save na instancji WordDocument. Określ ścieżkę do pliku, aby utworzyć nowy dokument z zastosowanymi modyfikacjami.
Czy do przetwarzania dokumentów WORD w języku C# muszę mieć zainstalowany pakiet Microsoft Office?
Nie, nie musisz mieć zainstalowanego pakietu Microsoft Office, aby przetwarzać dokumenty Word w języku C# przy użyciu IronWord. Biblioteka działa niezależnie od pakietu Microsoft Office, umożliwiając bezpośrednią pracę z plikami Word.
Które wersje .NET są kompatybilne z biblioteką do przetwarzania tekstu WORD?
IronWord jest kompatybilny z szeroką gamą wersji .NET, w tym .NET 8, 7, 6, Framework, Core i Azure. Dzięki temu spełnia on wymagania różnych projektów i środowisk.
Jak mogę uzyskać Licencję Trial na bibliotekę do przetwarzania tekstu w języku C#?
Aby uzyskać licencję Trial na IronWord, odwiedź stronę internetową Iron Software i podaj swój adres e-mail. Otrzymasz e-mailem klucz licencji Trial, który możesz dodać do pliku appsettings.json.




