C#'da Biçimlendirmeli Word Belgesi Nasil Okunur
Microsoft Word belgelerinde sıkça yazı tipi, stil ve görsel çekicilik katan çeşitli öğeler gibi zengin biçimlendirme bulunur. Iron Software'dan IronWord, sezgisel bir C# ve VB.NET Word ve Docx Belge API'sine sahip güçlü bir kütüphanedir. Word belgelerini oluşturmak, düzenlemek ve dışa aktarmak için Microsoft Office veya Word Interop kurulumuna gerek yoktur. IronWord, tam olarak .NET 8, 7, 6, Framework, Core ve Azure'u destekler. Bu, kütüphanenin makinede Word yüklemesine gerek duymadığı ve dosyaları bağımsız olarak okuduğu anlamına gelir. %C3/3C ile çalışıyorsanız ve biçimlendirmelerini korurken Word belgelerini okumanız gerekiyorsa, bu öğretici IronWord kütüphanesini kullanarak size yol gösterecektir.
C#'de Biçimlendirmeyle Word Belgesi Nasıl Okunur
- IronWord kütüphanesini yükleyerek Word belgelerini okuyun.
- IronWord kutuphanesinden
WordDocumentsınıfını kullanarak 'sample.docx' adlı Word belgesini yükleyin. - Yüklenmiş bir Word belgesi ile biçimlendirilmiş paragrafları okuyun.
- Ekstrakte edilmiş verileri ve format bilgilerini konsol çıktısında gösterin.
Ön Koşullar
- Visual Studio: Visual Studio veya başka bir C# geliştirme ortamı yüklü olduğundan emin olun.
- NuGet Paket Yöneticisi: Projenizde paketleri yönetmek için NuGet'i kullanabiliyor olun.
Adım 1: Yeni Bir C# Projesi Oluşturun
Word belgelerini okumak istediğiniz yeni bir C# konsol uygulaması oluşturun veya mevcut bir projeyi kullanın.
Konsol uygulaması şablonunu seçin ve ileri'ye tıklayın.

Kod için çözüm adını, proje adını ve yolunu sağlamak için 'İleri' butonuna tıklayın.

Ardından istenen .NET sürümünü seçin. En iyi uygulama her zaman mevcut olan en yeni sürümü seçmektir, ancak projenizin belirli 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 kutuphanesini yükleyin:
Install-Package IronWord
NuGet paketi, Visual Studio'nun NuGet Paket Yonetici'si kullanilarak asagida göstermedigi gibi de yuklenebilir.

Adım 3: Word Belgesini Biçimlendirme İle Okuma
Bir Word dosyasını okumak için önce yeni bir belge oluşturmamız ve ardından altıya bazı içerikler eklememiz gerekiyor.

Şimdi dosyayı proje dizinine kaydedin ve dosyanın özelliklerini, çıktıya kopyalanması için değiştirin.

Ş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}");
}
}
}
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
Yukarıdaki kod, IronWord kutuphanesi sınıfı WordDocument yapıcı yöntemi kullanılarak Word belgesini okur.
Çıktı

Açıklama
- Word Belgesini Açın: Word belgesini IronWord'dan
WordDocumentkullanarak yükleyin. - Paragraflar ve Çalışlar Arasında Dolaşın: Paragraflar ve çalışlar arasında dolaşmak için iç içe döngüler kullanın. Çalışlar belirli bir formatla olan metin bölümlerini temsil eder.
- Metin ve Biçimlendirilmeyi Ekstrakte Edin: Her çalıştan metin içeriğini çıkarın ve biçimlendirme özelliklerini kontrol edin. Bu örnekte, yazı tipi boyutunu ve kalın biçimlendirmeyi nasıl ekstrakte edeceğimizi gösterdik.
- İstisnaları Ele Alın: Herhangi bir istisna durumunu ele almak ve yazdırmak için bir try-and-catch bloğu kullanılır.
Yüklenmiş dosya, belgeleri yazdırmak için kullanılabilir, ayrıca stil nesnesinde yazı rengi değiştirilebilir.
Word Dosyalarından Tabloları Okuyun
Word belgelerinden tabloları 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}");
}
}
}
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
Burada, belge içindeki tüm tabloları almak ve ardından bunların üzerinden geçerek içeriklerini yazdırmak için WordDocument sınıfında Tables özelliğini kullanıyoruz.
Mevcut Metne Stil Ekleme
Aşağıdaki kod parçasında gösterildiği gibi IronWord kutuphanesini kullanarak, mevcut bir Word belgesine yeni stil bilgilerini 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}");
}
}
}
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
Burada bir TextStyle oluşturuyor ve bunu mevcut paragraf nesnesine ekliyoruz.
Word Belgesine Yeni Biçimlendirilmiş İçerik Ekleme
Aşağıdaki kod parçasında gösterildiği şekilde yüklenmiş bir Word belgesine 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}");
}
}
}
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
Burada stil bilgileri ile yeni TextRun ve Paragraph nesneleri oluşturup bunları yüklenen Word belgesine ekliyoruz.
Lisanslama (Ücretsiz Deneme Mevcut)
IronWord bedava deneme lisans anahtarınızı alın. Bu anahtar appsettings.json içine yerleştirilmelidir.
{
"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 ile gönderilecektir.

Sonuç
IronWord C# ile biçimlendirilmiş Word belgelerini okumanın uygun bir yolunu sağlar. Sağlanan kodu, üzerinde çalıştığınız belgelerin belirli gereksinimlerine ve karmaşıklığına göre genişletin. Bu eğitim, C# uygulamalarınıza kelime belgesi işleme için IronWord entegrasyonuna başlamak içindir.
Sıkça Sorulan Sorular
C#'ta biçimlendirme ile Word belgelerini nasıl okuyabilirim?
C#'ta biçimlendirme ile Word belgelerini okumak için IronWord kütüphanesini kullanın. Öncelikle NuGet Paket Yöneticisi üzerinden IronWord'ü yükleyin. WordDocument sınıfını kullanarak belgeyi yükleyin ve metin ile biçimlendirme detaylarını çıkarmak için paragraflar arasında dolaşın.
Word belgelerini okumak için bir C# projesi nasıl kurulur?
Word belgelerini okumak için bir C# projesi kurmak için Visual Studio veya başka bir C# geliştirme ortamını yükleyin. Projenize IronWord eklemek için NuGet Paket Yöneticisini kullanın. İçeriğine erişmek için WordDocument sınıfı ile Word belgelerini yükleyin.
C#'ta Word belgeleri okurken istisnaları nasıl işleyebilirim?
IronWord kullanarak C#'ta Word belgeleri okurken, belge işleme kodunuzun etrafını try-catch blokları uygulayarak istisnaları ele alın. Bu, çalışma zamanı hatalarını yönetmenize ve sağlam uygulama davranışı sağlamanıza yardımcı olacaktır.
C# kullanarak Word belgelerinden tablolar okuyabilir miyim?
Evet, IronWord kullanarak C#'ta Word belgelerinden tabloları okuyabilirsiniz. WordDocument sınıfının Tables özelliği aracılığıyla tablolara erişin ve gerektiğinde tablo verileri arasında dolaşın.
C# kullanarak bir Word belgesinde metin stillerini nasıl değiştirebilirim?
IronWord kullanarak bir Word belgesinde metin stillerini değiştirmek için bir TextStyle nesnesi oluşturun ve belirli metin çalıştırmalarına veya paragraflara uygulayın. Bu, fontları, boyutları ve diğer stil özniteliklerini özelleştirmenize olanak tanır.
C#'ta Word belgelerine yeni içerik eklemek mümkün müdür?
Evet, IronWord kullanarak C#'ta Word belgelerine yeni içerik ekleyebilirsiniz. Belgeye stilize edilmiş içerik eklemek için TextRun ve Paragraph nesneleri oluşturun ve değişikliklerinizi kaydetmeden önce belgeye ekleyin.
C#'ta bir Word belgesine yapılan değişiklikleri nasıl kaydederim?
IronWord kullanarak bir Word belgesini düzenledikten sonra, WordDocument örneğinde Save yöntemini çağırarak değişikliklerinizi kaydedin. Belirtilen dosya yoluna uygulanmış değişikliklerle yeni bir belge oluşturmak için kaydedin.
C#'ta Word belgelerini işlemek için Microsoft Office kurulu olması gerekiyor mu?
Hayır, C#'ta IronWord kullanarak Word belgelerini işlemek için Microsoft Office kurulmasına gerek yoktur. Kütüphane, Microsoft Office'ten bağımsız çalışarak Word dosyalarıyla doğrudan çalışmanıza olanak tanır.
Bir Word işleme kütüphanesiyle uyumlu olan .NET sürümleri nelerdir?
IronWord, .NET 8, 7, 6, Framework, Core ve Azure dahil olmak üzere geniş bir .NET sürümleri yelpazesi ile uyumludur. Bu, çeşitli proje gereksinimlerine ve ortamlara uygun olmasını sağlar.
C#'ta bir Word işleme kütüphanesi için deneme lisansı nasıl elde edilir?
IronWord için bir deneme lisansı almak amacıyla Iron Software web sitesini ziyaret edin ve e-posta adresinizi sağlayın. E-posta yoluyla size bir deneme lisans anahtarı gönderilecek ve bu anahtarı appsettings.json dosyanıza ekleyebilirsiniz.




