Zum Fußzeileninhalt springen
IRONWORD VERWENDEN

Wie man Word-Dokumente ohne Office Interop in C# erstellt

Microsoft Word-Dokumente werden häufig für verschiedene Zwecke verwendet, von formellen Geschäftsberichten bis hin zu persönlichen Briefen. In C# müssen Entwickler häufig Microsoft Word-Dokumente programmatisch erzeugen. Windows-Anwendungsentwickler haben traditionell das Microsoft Office Interop verwendet, um Word-Dokumente mit C# zu generieren und zu erstellen.

Dieses Vorgehen ist jedoch nicht für jeden zugänglich, und Entwickler können auf einem Betriebssystem oder auf einer Linux-Maschine arbeiten, wo die Microsoft Office-Schnittstelle nicht verfügbar ist. In diesen Fällen müssen Entwickler andere Bibliotheken erkunden, die unabhängig auf verschiedenen Plattformen arbeiten können. One such powerful library for working with Word files programmatically is IronWord, from Iron Software.

IronWord bietet robuste Funktionen für das Arbeiten mit Word-Dokumenten in .NET-Anwendungen und kann auf verschiedenen Plattformen und Docker-Bildern/Controllern basierend auf Linux ausgeführt werden. Mit IronWord, das über eine intuitive C#, VB.NET Word und Docx Document API verfügt, besteht keine Notwendigkeit, Microsoft Office, Office Automation oder Word Interop zu installieren, um Word-Dokumentdateien zu erstellen, zu bearbeiten und zu exportieren. IronWord unterstützt vollständig .NET 8, 7, 6, Framework, Core und Azure.

Dieser Artikel wird die Erstellung von Word-Dokumenten in C# mithilfe der IronWord-Bibliothek untersuchen.

Wie man Word-Dokumente ohne Office Interop in C# erstellt

  1. Erstellen Sie ein neues C# Projekt.
  2. Installieren Sie die IronWord Bibliothek.
  3. Erstellen Sie ein Word-Dokument mit der IronWord-Bibliothek.
  4. Fügen Sie dem nun vorhandenen Dokument Inhalt hinzu.
  5. Speichern Sie das erstellte Word-Dokument.
  6. Öffnen und zeigen Sie das erstellte Word-Dokument 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 Sie ein neues C#-Projekt

Erstellen Sie eine neue C#-Konsolenanwendung oder verwenden Sie ein bestehendes Projekt, in dem Sie das Word-Dokument generieren möchten.

Wählen Sie die Vorlage für Konsolenanwendungen und klicken Sie auf Weiter.

Wie man Word-Dokumente ohne Office Interop in C# erstellt: Abbildung 1 - Konsolen-App-Vorlage zur Erstellung eines neuen Projekts

Im nächsten Schritt können Sie die Namen der Lösung und des Projekts angeben.

Wie man Word-Dokumente ohne Office Interop in C# erstellt: Abbildung 2 - Projekt mit Projektlösungs- und Projektnamen konfigurieren

Wählen Sie die .NET-Version aus und klicken Sie auf "Erstellen".

Wie man Word-Dokumente ohne Office Interop in C# erstellt: Abbildung 3 - Projekt mit der richtigen .NET-Version erstellen

Schritt 2: Installieren der IronWord-Bibliothek

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

Install-Package IronWord -Version 2024.1.2

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

Wie man Word-Dokumente ohne Office Interop in C# erstellt: Abbildung 4 - IronWord mit dem VS-Paketmanager installieren

Schritt 3: Erstellen und Speichern eines Word-Dokuments mit der IronWord-Bibliothek

Beginnen wir mit dem einfachen Beispiel, wie man ein Word-Dokument mit der IronWord-Bibliothek erstellt. Der folgende Code zeigt, wie man ein grundlegendes Word-Dokument mit einem einzigen Absatz erstellt, der den Text "Hello, World!" enthält.

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.docx
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.docx
Imports 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.docx
$vbLabelText   $csharpLabel

Nach der Ausführung des obigen Codebeispiels wird die neue Dokumentdatei example.docx erstellt und die Ausgabe ist unten gezeigt.

Wie man Word-Dokumente ohne Office Interop in C# erstellt: Abbildung 5 - Word-Dokument, das durch den obigen Code erstellt wurde.

Dies ist ein grundlegendes Beispiel für die Generierung einer Word-Dokumentdatei mit IronWord. Für weitere Informationen können Sie die Dokumentation lesen.

Hinzufügen von Absätzen mit Stil zu einem Word-Dokument

Da wir nun wissen, wie man ein einfaches Word-Dokument mit IronWord erstellt, fügen wir Absätze und formatierten Text hinzu.

TextRun kann auch Stil-Daten übernehmen, um die visuelle Darstellung des Textes zu verbessern. Text kann mit Stilen wie Durchgestrichenheit, Fett, Kursiv und Unterstrichen formatiert werden.

Ändern und fügen Sie den unten stehenden Code zu dem Programm hinzu, das Sie zuvor erstellt haben.

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.docx
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.docx
Imports 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.docx
$vbLabelText   $csharpLabel

Hinzufügen einer Tabelle zu einem Word-Dokument

Für eine klare Darstellung von Daten kann sie auch in einem Raster dargestellt werden. Wenn Daten in einem Raster angeordnet sind, wird dies als Tabelle bezeichnet. Mit IronWord können wir Tabellen und Bilder zum Word-Dokument hinzufügen, wie unten gezeigt:

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.docx
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.docx
Imports 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.docx
$vbLabelText   $csharpLabel

Im obigen Beispiel haben wir eine Tabelle mit Rändern zu einem Word-Dokument hinzugefügt.

Hinzufügen von Bildern zu einem Word-Dokument

Bilder verbessern die Präsentation des Dokuments und können mehr Farben und visuelle Attraktivität hinzufügen.

Bilder können programmatisch zu einem Word-Dokument hinzugefügt werden, wie im untenstehenden Code gezeigt:

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.docx
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.docx
Imports 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.docx
$vbLabelText   $csharpLabel

Hier fügen wir ein Bild mit IronWord.Models.Image mit einer Höhe und Breite von 200 Pixeln zu einem Absatz hinzu.

Lizenzierung (Kostenlose Testversion verfügbar)

IronWord benötigt eine Lizenz zur Nutzung. Beantragen Sie einen Testschlüssel von der Iron Software-Website. 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. Nach der Eingabe Ihrer E-Mail-Adresse wird der Schlüssel per E-Mail zugestellt.

Wie man Word-Dokumente ohne Office Interop in C# erstellt: Abbildung 6 - Popup bei erfolgreicher Einreichung des Testformulars

Abschluss

Die Erstellung von Word-Dokumenten in C# mit Hilfe der IronWord-Bibliothek bietet eine flexible und effiziente Möglichkeit, Dokumente ohne Abhängigkeit von Microsoft Office zu generieren. Egal ob Sie einfache Briefe oder komplexe Berichte mit Tabellen und Bildern erstellen müssen, IronWord ermöglicht Ihnen dies programmatisch. Dieser Artikel bietet ein umfassendes Tutorial zur Erstellung von Word-Dokumenten. Mit IronWord haben Sie die Möglichkeit, die Erstellung von Word-Dokumenten zu automatisieren, wodurch Ihre C#-Anwendungen vielseitiger und produktiver werden.

Und für Entwickler, die PDF-Dateien manipulieren möchten, um mit ihren generierten Word-Dokumenten zu arbeiten, schauen Sie nicht weiter als IronPDF, eine weitere C#-Bibliothek, die von Iron Software produziert wurde.

Häufig gestellte Fragen

Wie kann ich Word-Dokumente in C# erstellen, ohne Microsoft Office Interop zu verwenden?

Sie können Word-Dokumente in C# erstellen, ohne Microsoft Office Interop zu verwenden, indem Sie die IronWORD-Bibliothek nutzen. Diese Bibliothek ermöglicht es Ihnen, Word-Dokumente programmatisch zu generieren, zu bearbeiten und zu speichern, ohne dass eine Installation von Microsoft Office erforderlich ist.

Was sind die Vorteile der Verwendung von IronWORD gegenüber Microsoft Office Interop?

IronWORD bietet die Flexibilität, auf Nicht-Windows-Plattformen wie Linux zu laufen, wo Microsoft Office Interop nicht verfügbar ist. Es eliminiert auch die Abhängigkeit von einer Installation von Microsoft Office, was den Entwicklungsprozess vereinfacht.

Wie fange ich an, ein Word-Dokument mit IronWORD zu erstellen?

Um ein Word-Dokument mit IronWORD zu erstellen, installieren Sie zuerst die IronWORD-Bibliothek über den NuGet Paket-Manager in Ihrem C#-Projekt. Verwenden Sie dann die IronWORD-API, um Word-Dokumente programmatisch zu erstellen und zu manipulieren.

Kann ich IronWORD mit den neuesten .NET-Versionen verwenden?

Ja, IronWORD ist mit verschiedenen .NET-Versionen kompatibel, einschließlich .NET 8, 7, 6, Framework, Core und Azure, was es Ihnen ermöglicht, es in moderne C#-Anwendungen zu integrieren.

Wie kann ich formatierten Text mit IronWORD zu einem Word-Dokument hinzufügen?

IronWORD ermöglicht es Ihnen, formatierten Text mit den TextRun und TextStyle Klassen hinzuzufügen. Diese Klassen ermöglichen es, Stile wie fett, kursiv und unterstrichen auf bestimmte Textsegmente in Ihrem Word-Dokument anzuwenden.

Ist es möglich, Tabellen in Word-Dokumenten mit IronWORD einzufügen?

Ja, Sie können Tabellen in Word-Dokumenten mit IronWORD einfügen. Die Bibliothek erlaubt Ihnen, Tabellen mit Zeilen und Zellen zu definieren, und Sie können deren Aussehen mit Rahmen und anderen Stilen anpassen.

Wie fügt man Bilder in ein Word-Dokument mit IronWORD ein?

Um Bilder in ein Word-Dokument mit IronWORD einzufügen, können Sie die IronWord.Models.Image Klasse verwenden, um Bilder mit angegebenen Abmessungen in Absätze einzubetten und so den visuellen Inhalt Ihres Dokuments zu verbessern.

Gibt es eine Testversion von IronWORD zur Bewertung?

Ja, Iron Software bietet eine kostenlose Testversion von IronWORD an, die Sie von ihrer Website herunterladen können. Diese Testversion ermöglicht es Ihnen, die Funktionen und Fähigkeiten der Bibliothek zu bewerten, bevor Sie einen Kauf tätigen.

Welche weiteren Bibliotheken zur Dokumentenbearbeitung bietet Iron Software an?

Neben IronWORD bietet Iron Software IronPDF an, eine Bibliothek zum Bearbeiten von PDF-Dateien. Zusammen bieten diese Bibliotheken umfassende Lösungen für die Bearbeitung von Word- und PDF-Dokumenten in C#-Anwendungen.

Jordi Bardia
Software Ingenieur
Jordi ist am besten in Python, C# und C++ versiert. Wenn er nicht bei Iron Software seine Fähigkeiten einsetzt, programmiert er Spiele. Mit Verantwortung für Produkttests, Produktentwicklung und -forschung trägt Jordi mit immensem Wert zur kontinuierlichen Produktverbesserung bei. Die abwechslungsreiche Erfahrung hält ihn gefordert und engagiert, ...
Weiterlesen