3 Biblioteki Word w C# (zaktualizowana lista dla deweloperów)
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 C#) Czytać Dokument Word Z Formatowaniem
- Zainstaluj bibliotekę IronWord, aby odczytywać dokumenty Word.
- Załaduj 'sample.docx', dokument Word przy użyciu 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 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:
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}");
}
}
}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 ClassPowyższy kod odczytuje dokument Word przy użyciu metody konstruktora klasy WordDocument z biblioteki IronWord.
Wynik

Wyjaśnienie
- Otwórz dokument Word: Załaduj dokument Word przy użyciu
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}");
}
}
}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 ClassTutaj używamy właściwości Tables na 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}");
}
}
}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 ClassTutaj tworzymy TextStyle i dodajemy go do istniejącego obiektu paragrafu.
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}");
}
}
}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 ClassTutaj tworzymy nowe obiekty TextRun i Paragraph ze stylizacją i dodajemy je do załadowanego dokumentu Word.
Licencjonowanie (dostępna bezpłatna wersja próbna)
Zdobądź bezplatną licencję probną IronWord. Ten klucz musi być umieszczony 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.

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podręczników.
Powiązane artykuły

