如何在 C# 中讀取帶有格式的 Word 文檔
Microsoft Word 文件通常包含豐富的格式,例如字體、樣式和各種元素,使其在視覺上具有吸引力。 IronWord 是Iron Software出品的一款功能強大的函式庫,它擁有直覺的 C# 和 VB.NET Word 和 Docx 文件 API。 無需安裝 Microsoft Office 或 Word Interop 即可建立、編輯和匯出 Word 文件。 IronWord 完全支援 .NET 8、7、6、Framework、Core 和 Azure。 這意味著該庫不需要在電腦上安裝 Word,並且可以獨立讀取檔案。 如果您正在使用 C# 並且需要讀取 Word 文件並保留其格式,本教學將指導您使用IronWord庫完成此過程。
如何在 C# 中讀取帶有格式的 Word 文檔
- 安裝 IronWord 庫以讀取 Word 文件。
- 使用 IronWord 庫中的
WordDocument類別載入輸入 Word 文件"sample.docx"。 - 使用載入的 Word 文件閱讀帶有格式的段落。
- 在控制台輸出中顯示擷取的資料及其格式資訊。
先決條件
- Visual Studio:確保您已安裝 Visual Studio 或任何其他 C# 開發環境。
- NuGet 套件管理器:確保您可以使用 NuGet 管理專案中的套件。
步驟 1:建立一個新的 C# 項目
建立一個新的 C# 控制台應用程序,或使用一個現有的專案來讀取 Word 文件。
選擇控制台應用程式模板,然後按一下下一步。
如何在 C# 中讀取帶有格式的 Word 文件:圖 1 - 建立一個新的 C# 項目
按一下"下一步"按鈕,提供解決方案名稱、專案名稱和程式碼路徑。
如何在 C# 中讀取帶有格式的 Word 文件:圖 2 - 配置新項目
然後選擇所需的 .NET 版本。 最佳實踐是始終選擇可用的最新版本,但如果您的專案有特定要求,請使用必要的 .NET 版本。
步驟 2:安裝 IronWord 函式庫
開啟您的 C# 項目,並使用 NuGet 套件管理器控制台安裝 IronWord 庫:
Install-Package IronWord
也可以使用 Visual Studio 的 NuGet 套件管理器安裝 NuGet 套件,如下圖所示。
步驟 3:閱讀帶有格式的 Word 文檔
要讀取 Word 文件,首先需要建立一個新文檔,然後在其中添加一些內容,如下所示。
如何在 C# 中讀取帶有格式的 Word 文檔:圖 5 - 建立的範例文檔
現在將檔案儲存到專案目錄,並更改檔案屬性,將其複製到輸出目錄。
如何在 C# 中讀取帶有格式的 Word 文件:圖 6 - 文件屬性應如下所示
現在將以下程式碼片段加入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}");
}
}
}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}");
}
}
}上述程式碼使用 IronWord 函式庫類別WordDocument建構函式方法讀取 Word 文件。
輸出
解釋
1.開啟 Word 文件:使用 IronWord 中的WordDocument載入 Word 文件。 2.遍歷段落和段落:使用巢狀循環遍歷段落和段落。 樂段代表具有特定格式的文字部分。 3.提取文字和格式:從每次運行中提取文字內容並檢查格式屬性。 在這個例子中,我們示範如何提取字體大小和粗體格式。 4.處理異常:使用 try-and-catch 區塊來處理任何異常並列印它們。
載入的文件可用於列印文檔,我們也可以在樣式物件中變更字體顏色。
從 Word 文件中讀取表格
我們也可以讀取 Word 文件中的表格。 將以下程式碼片段加入程式中。
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}");
}
}
}這裡我們使用WordDocument類別的Tables屬性來取得文件中的所有表格,然後遍歷它們並列印其內容。
為現有文字新增樣式
我們可以使用 IronWord 庫為現有的 Word 文件添加新的樣式訊息,如下面的程式碼片段所示。
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}");
}
}
}這裡我們建立一個TextStyle並將其加入到現有的段落物件中。
在 Word 文件中新增新的樣式內容
我們可以為已載入的 Word 文件中新增內容,如下面的程式碼片段所示。
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}");
}
}
}在這裡,我們將建立帶有樣式資訊的TextRun和Paragraph對象,並將它們新增至已載入的 Word 文件中。
授權許可(提供免費試用)
取得您的 IronWord 免費試用授權金鑰。 需要將此鍵放置在appsettings.json中。
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}請提供您的電子郵件地址以取得試用許可證。 提交您的電子郵件地址後,金鑰將透過電子郵件發送給您。
結論
IronWord提供了一種便捷的方式,可以使用 C# 讀取帶有格式的 Word 文件。 根據您的具體需求和您正在處理的文件的複雜性,擴展提供的程式碼。 本教學課程旨在為將IronWord整合到您的 C# 應用程式中以進行 Word 文件處理提供一個起點。
常見問題解答
如何在C#中讀取帶有格式的Word文件?
若要在 C# 中讀取帶有格式的 Word 文檔,請使用 IronWord 庫。首先透過 NuGet 套件管理器安裝 IronWord。使用WordDocument類別載入文檔,並遍歷段落以提取文字和格式資訊。
如何設定一個用於讀取 Word 文件的 C# 專案?
若要設定一個用於讀取 Word 文件的 C# 項目,請安裝 Visual Studio 或其他 C# 開發環境。使用 NuGet 套件管理器將 IronWord 新增至您的專案中。使用WordDocument類別載入 Word 文件以存取其內容。
在 C# 中讀取 Word 文件時如何處理異常?
使用 IronWord 以 C# 格式讀取 Word 文件時,請在文件處理程式碼周圍新增 try-catch 區塊來處理例外狀況。這有助於管理運行時錯誤,並確保應用程式的穩定運作。
我可以使用 C# 讀取 Word 文件中的表格嗎?
是的,您可以使用 C# 中的 IronWord 來讀取 Word 文件中的表格。透過WordDocument類別的Tables屬性存取表格,並根據需要遍歷表格資料。
如何使用 C# 修改 Word 文件中的文字樣式?
使用 IronWord,您可以透過建立TextStyle物件並將其套用至特定的文字行或段落來修改 Word 文件中的文字樣式。這樣,您可以自訂字體、大小和其他樣式屬性。
是否可以在 C# 中為 Word 文件新增內容?
是的,您可以使用 C# 中的 IronWord 為 Word 文件新增內容。建立TextRun和Paragraph對象,即可在儲存變更之前向文件新增樣式化內容。
如何在 C# 中儲存 Word 文件的修改?
使用 IronWord 編輯 Word 文件後,呼叫WordDocument實例的Save方法儲存變更。指定檔案路徑,即可建立一個包含已套用修改的新文件。
我是否需要安裝 Microsoft Office 才能在 C# 中處理 Word 文件?
不,您無需安裝 Microsoft Office 即可使用 IronWord 在 C# 中處理 Word 文件。該程式庫獨立於 Microsoft Office 運行,可讓您直接處理 Word 文件。
哪些 .NET 版本與文字處理程式庫相容?
IronWord 與多種 .NET 版本相容,包括 .NET 8、7、6、Framework、Core 和 Azure。這確保了它能夠滿足各種專案需求和環境。
如何獲得 C# 文字處理庫的試用許可證?
若要取得 IronWord 的試用許可證,請造訪 Iron Software 網站並提供您的電子郵件地址。您將透過電子郵件收到試用許可證金鑰,您可以將其新增至appsettings.json檔案。







