Jak odczytac dokument Word z formatowaniem w C#
Dokumenty Microsoft Word są powszechnie stosowane do różnych celów, od formalnych raportów biznesowych po osobiste listy. W C# programiści często muszą generować dokumenty Microsoft Word programatycznie. Twórcy aplikacji na Windows tradycyjnie używali Microsoft Office Interop do generowania i tworzenia dokumentów Word z użyciem C#.
Jednak to podejście nie jest dostępne dla wszystkich, a programiści mogą pracować na systemie operacyjnym lub maszynie z systemem Linux, gdzie interfejs Microsoft Office nie jest dostępny. W takich przypadkach programiści muszą poszukać innych bibliotek, które mogą niezależnie działać na różnych platformach. Jedną z takich potężnych bibliotek do pracy z plikami Word programatycznie jest IronWord, od Iron Software.
IronWord zapewnia solidną funkcjonalność do pracy z dokumentami Word w aplikacjach .NET i może działać na różnych platformach oraz obrazach/kontenerach docker opartych na Linux. Dzięki IronWord, które ma intuicyjne API dokumentów Word i Docx w języku C#, VB.NET, nie ma potrzeby instalowania Microsoft Office, automatyzacji Office ani Word Interop, aby tworzyć, edytować i eksportować pliki dokumentów Word. IronWord w pełni obsługuje .NET 8, 7, 6, Framework, Core oraz Azure.
Ten artykuł bada tworzenie dokumentów Word w C# przy użyciu biblioteki IronWord.
How to Create Word Documents Without Office Interop in C#
- Utwórz nowy projekt w języku C#.
- Zainstaluj bibliotekę IronWord.
- Utwórz dokument Word przy użyciu biblioteki IronWord.
- Dodaj zawartość do istniejącego dokumentu.
- Zapisz utworzony dokument Word.
- Otwórz i wyświetl utworzony dokument Word.
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ą C# lub użyj istniejącego projektu, w którym chcesz generować dokument Word.
Wybierz szablon aplikacji konsolowej i kliknij Dalej.

W kolejnym kroku możesz podać nazwy rozwiązań i projektów.

Wybierz wersję .NET i kliknij "Utwórz".

Krok 2: Zainstaluj bibliotekę IronWord
Otwórz swój projekt C# i zainstaluj bibliotekę IronWord używając konsoli Menedżera Pakietów NuGet:
Pakiet NuGet można również zainstalować przy użyciu Menedżera Pakietów Visual Studio, jak pokazano poniżej.

Krok 3: Tworzenie i zapisywanie dokumentu Word przy użyciu biblioteki IronWord
Zacznijmy od prostego przykładu tworzenia dokumentu Word przy użyciu biblioteki IronWord. Poniższy kod pokazuje, jak stworzyć podstawowy dokument Word z jednym akapitem zawierającym tekst "Hello, World!".
using IronWord;
using IronWord.Models;
// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");
// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);
// Create a new Word document object with the paragraph
WordDocument doc = new WordDocument(paragraph);
// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docxImports IronWord
Imports IronWord.Models
' Create a text run instance with "Hello, World!" content
Private textRun As New TextRun("Hello, World!")
' Create a paragraph and add the text run to it
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)
' Create a new Word document object with the paragraph
Dim doc As New WordDocument(paragraph)
' Save the document as a .docx file
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docxPo wykonaniu powyższego przykładu kodu nowy plik dokumentu, example.docx, jest tworzony i wynik przedstawiony jest poniżej.

To podstawowy przykład generowania pliku dokumentu Word przy użyciu IronWord. Więcej informacji można znaleźć w Dokumentacji.
Dodawanie akapitów ze stylami do dokumentu Word
Teraz, gdy wiemy, jak stworzyć prosty dokument Word przy użyciu IronWord, dodajmy akapity i stylizowany tekst.
TextRun może również przyjmować dane dotyczące stylu, ulepszając wizualną reprezentację tekstu. Tekst można ustawić za pomocą stylów, takich jak przekreślenie, pogrubienie, kursywa i podkreślenie.
Zmień i dodaj poniższy kod do programu, który wcześniej stworzyłeś.
using IronWord;
using IronWord.Models;
// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);
// Configure and add italic text
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);
// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);
// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docxImports IronWord
Imports IronWord.Models
' Create text runs with different styles
Private textRun As New TextRun("Hello, World!") ' Simple string
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)
' Configure and add italic text
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)
' Configure and add bold text
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)
' Add text runs to the paragraph
paragraph.AddTextRun(introText)
paragraph.AddTextRun(italicText)
paragraph.AddTextRun(boldText)
' Create and save the new Word document
Dim doc As New WordDocument(paragraph)
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docxDodawanie tabeli do dokumentu Word
Dla przejrzystego przedstawienia danych można je również przedstawić w postaci siatki. Kiedy dane są uporządkowane w formie siatki, nazywa się to tabelą. Korzystając z IronWord, możemy dodać tabele i obrazy do dokumentu Word, jak pokazano poniżej:
using IronWord;
using IronWord.Models;
// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");
// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));
// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
BorderValue = IronWord.Models.Enums.BorderValues.Thick,
BorderSize = 5
};
// Set table borders
TableBorders tableBorders = new TableBorders
{
TopBorder = borderStyle,
RightBorder = borderStyle,
BottomBorder = borderStyle,
LeftBorder = borderStyle
};
cell.Borders = tableBorders;
// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells
// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);
// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docxImports IronWord
Imports IronWord.Models
' Create a table cell with sample text
Private cell As New TableCell()
Private textRun As New TextRun("Sample text")
' Add text run to the cell as a paragraph
cell.AddContent(New Paragraph(textRun))
' Configure cell border style
Dim borderStyle As New BorderStyle With {
.BorderColor = New IronColor(IronSoftware.Drawing.Color.Black),
.BorderValue = IronWord.Models.Enums.BorderValues.Thick,
.BorderSize = 5
}
' Set table borders
Dim tableBorders As New TableBorders With {
.TopBorder = borderStyle,
.RightBorder = borderStyle,
.BottomBorder = borderStyle,
.LeftBorder = borderStyle
}
cell.Borders = tableBorders
' Create a table row and add cells to it
Dim row As New TableRow()
row.AddCell(cell) ' Add the first cell
row.AddCell(cell) ' Add the second cell, duplicating to mimic a row with two identical cells
' Create a table and add the row to the table
Dim table As New Table()
table.AddRow(row)
' Create and save a Word document using the table
Dim doc As New WordDocument(table)
doc.SaveAs("Document.docx") ' Saves the file to disk with the name Document.docxW powyższym przykładzie dodaliśmy tabelę do dokumentu Word za pomocą obramowania.
Dodawanie obrazów do dokumentu Word
Obrazy wzbogacają prezentację dokumentu i mogą dodać więcej kolorów i atrakcyjności wizualnej.
Obrazy mogą być dodawane programatycznie do dokumentu Word przy użyciu IronWord, jak pokazano w poniższym kodzie:
using IronWord;
using IronWord.Models;
// Load a new document
WordDocument doc = new WordDocument();
// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
Width = 200, // Set image width in pixels
Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document
// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docxImports IronWord
Imports IronWord.Models
' Load a new document
Private doc As New WordDocument()
' Configure and add image to the document
Private image As New IronWord.Models.Image("SalesChart.jpg") With {
.Width = 200,
.Height = 200
}
Private paragraph As New Paragraph()
paragraph.AddImage(image) ' Add image to paragraph
doc.AddParagraph(paragraph) ' Add paragraph to the document
' Save the document as a .docx file
doc.SaveAs("save_document.docx") ' Saves the file to disk with the name save_document.docxTutaj dodajemy obraz za pomocą IronWord.Models.Image z wysokością i szerokością 200 pikseli do akapitu.
Licencjonowanie (dostępna bezpłatna wersja próbna)
IronWord wymaga licencji do używania. Uzyskaj klucz testowy z strony internetowej Iron Software. 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
Tworzenie dokumentów Word w C# przy użyciu biblioteki IronWord zapewnia elastyczny i wydajny sposób generowania dokumentów bez polegania na Microsoft Office. Niezależnie od tego, czy potrzebujesz stworzyć proste listy czy skomplikowane raporty z tabelami i obrazami, IronWord pozwala osiągnąć to programatycznie. Ten artykuł dostarcza kompleksowy przewodnik na temat tworzenia dokumentów Word. Dzięki IronWord masz możliwość automatyzacji tworzenia dokumentów Word, czyniąc swoje aplikacje C# bardziej wszechstronnymi i produktywnymi.
A dla deweloperów interesujących się manipulacją plikami PDF w celu pracy w połączeniu z generowanymi dokumentami Word, nie szukaj dalej niż IronPDF, kolejna biblioteka C# produkowana przez Iron Software.

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

