3 C# Word Kütüphanesi (Gelistriciler İçin Guncel Liste)
Microsoft Word belgeleri genellikle fontlar, stiller ve onları görsel olarak çekici hale getiren çeşitli öğeleri içeren zengin bir biçimlendirme sunar. IronWord, Iron Software ürünü olan ve sezgisel C# ve VB.NET Word ve Docx Belge API'sine sahip güçlü bir kütüphanedir. Word belgeleri oluşturmak, düzenlemek ve dışa aktarmak için Microsoft Office veya Word Interop'u yüklemeye gerek yoktur. IronWord, .NET 8, 7, 6, Framework, Core ve Azure'u tam destekler. Bu, kütüphanenin makinede Word yüklü olmayacağını ve dosyaları bağımsız olarak okuyacağını gösterir. C# ile çalışıyorsanız ve biçimlendirmeyi koruyarak Word belgelerini okumanız gerekiyorsa, bu öğretici IronWord kütüphanesini kullanarak sizi bu sürece yönlendirecek.
Word Belgesini Biçimlendirmeyle (C# ile) Nasıl Okunur
- Word belgelerini okumak için IronWord kütüphanesini yükleyin.
- IronWord kütüphanesinden
WordDocumentsınıfını kullanarak, girdi olan 'sample.docx' Word belgesini yükleyin. - Yüklenen Word belgesini kullanarak biçimlendirmeli paragrafları okuyun.
- Konsol çıktısında format bilgisi ile çıkarılmış verileri gösterin.
Gereksinimler
- Visual Studio: Visual Studio veya başka bir C# geliştirme ortamı yüklendiğinden emin olun.
- NuGet Paket Yöneticisi: Projenizde paketleri yönetmek için NuGet'i kullanabileceğinizden emin olun.
Adım 1: Yeni C# Projesini Oluştur
Yeni bir C# konsol uygulaması oluşturun veya Word belgelerini okumak istediğiniz mevcut bir projeyi kullanın.
Konsol uygulama şablonunu seçin ve devam etmek için tıklayın.

Çözüm adı, proje adı ve kodun yolu için 'İleri' Düğmesine tıklayın.

Ardından, istenen .NET sürümünü seçin. Her zaman en son sürümü seçmek en iyi uygulamadır, ancak projenizin özel gereksinimleri varsa gerekli .NET sürümünü kullanın.

Adım 2: IronWord Kütüphanesini Yükleyin
C# projenizi açın ve NuGet Paket Yöneticisi Konsolunu kullanarak IronWord kütüphanesini yükleyin:
NuGet paketi, aşağıda gösterildiği gibi Visual Studio'nun NuGet Paket Yöneticisi kullanılarak da kurulabilir.

3. Adım: Word Belgesini Formatlama ile Okuma
Bir Word dosyasını okumak için önce yeni bir belge oluşturmalı ve ardından aşağıda belirtildiği gibi içerik eklemeliyiz.

Dosyayı proje dizinine kaydedin ve çıktıya kopyalamak için dosyanın özelliklerini değiştirebileceğiniz gibi:

Şimdi aşağıdaki kod parçasını program.cs dosyasına ekleyin:
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 ClassYukarıdaki kod, IronWord kütüphanesi sınıfı WordDocument yapıcı yöntemini kullanarak Word belgesini okur.
Çıktı

Açıklama
- Word Belgesini Açın: IronWord'dan
WordDocumentkullanarak Word belgesini yükleyin. - Paragraflar ve Çalıştırmalar Arasında Yinele: Paragraflar ve çalışmalar arasında yinelemek için iç içe döngüler kullanın. Çalışmalar, belirli bir format içeren metin parçalarını temsil eder.
- Metin ve Biçimlendirmeyi Ayıklayın: Her çalışmadan metin içeriğini çıkarın ve format özelliklerini kontrol edin. Bu örnekte, font boyutunu ve kalın biçimlendirmeyi nasıl çıkaracağımızı gösterdik.
- İstisnaları Yönet: İstisnaları ele almak ve yazdırmak için bir try-and-catch bloğu kullanılır.
Yüklenen dosya, belgeleri yazdırmak için kullanılabilir, stil nesnesinde yazı tipi rengini de değiştirebiliriz.
Word Dosyalarından Tablo Okuma
Word belgelerinden tablo da okuyabiliriz. Aşağıdaki kod parçasını programa ekleyin.
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 ClassBurada belgede bulunan tüm tabloları almak için WordDocument sınıfı üzerinde Tables özelliğini kullanıyoruz, ardından bunlar arasında döngü yaparak içeriklerini yazdırıyoruz.
Mevcut Metine Stil Ekleme
Aşağıda gösterildiği kod parçasında olduğu gibi, IronWord kütüphanesini kullanarak mevcut bir Word belgesine yeni stil bilgisi ekleyebiliriz.
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 ClassBurada bir TextStyle oluşturuyoruz ve mevcut paragraf nesnesine ekliyoruz.
Word Belgesine Yeni Stilize Edilmiş İçerik Ekleme
Yüklenen bir Word belgesine aşağıda gösterilen kod parçasında olduğu gibi yeni içerik ekleyebiliriz.
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 ClassBurada stil bilgisi içeren yeni TextRun ve Paragraph nesneleri oluşturuyoruz ve yüklenen Word belgesine ekliyoruz.
Lisanslama (Ücretsiz Deneme Mevcuttur)
Ücretsiz IronWord deneme lisans anahtarınızı alın. Bu anahtarın appsettings.json içine yerleştirilmesi gerekiyor.
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}
Deneme lisansı almak için e-posta adresinizi sağlayın. E-posta kimliğinizi gönderdikten sonra, anahtar e-posta yoluyla teslim edilecektir.

Sonuç
IronWord, C# dilinde formatlama ile Word belgelerini okumak için uygun bir yöntem sunar. Belirli gereksinimlerinize ve üzerinde çalıştığınız belgelerin karmaşıklığına göre sağlanan kodu genişletin. Bu öğretici, C# uygulamalarınızda Word belge işleme için IronWord'u entegre etmeye başlamak için bir başlangıç noktası olarak hizmet eder.

Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.
İlgili Makaleler

