IRONSOFTWAREHOME
USING IRONWORD

3 個 C# Word 庫(為開發人員更新的列表)

Curtis Chau
Curtis Chau
Updated: 2026年5月8日

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文件

  1. 安裝IronWord程式庫以讀取Word文件。
  2. 使用IronWord程式庫中的WordDocument類載入輸入Word文件'sample.docx'。
  3. 使用已載入的Word文件讀取格式化的段落。
  4. 在控制台輸出中顯示具有格式資訊的提取資料。

先決條件

  1. **Visual Studio:**請確保您已安裝Visual Studio或任何其他C#開發環境。
  2. **NuGet包管理器:**確保您能夠使用NuGet管理項目中的包

步驟1:建立新的C#專案

建立新的C#控制台應用程式或使用現有的項目,在那里您希望讀取Word文件。

選擇控制台應用程式範本然後點擊下一步。

如何在C#中讀取具有格式的Word文件:圖1 - 建立新的C#項目

單擊"下一步"按鈕以提供解決方案名稱、項目名稱和程式碼的路徑。

如何在C#中讀取具有格式的Word文件:圖2 - 配置新項目

然後選擇所需的.NET版本。 最好的做法是始終選擇可用的最新版本,雖然如果您的項目有特定需求,那麼使用必要的.NET版本。

如何在C#中讀取具有格式的Word文件:圖3 - 選擇必要的.NET版本型別

步驟2:安裝IronWord程式庫

打開您的C#項目並使用NuGet包管理器控制台安裝IronWord程式庫:

PM > Install-Package IronWord

NuGet包也可以使用Visual Studio的NuGet包管理器進行安裝,如下所示。

如何在C#中讀取具有格式的Word文件:圖4 - 通過NuGet包管理器安裝IronWord

步驟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}");
        }
    }
}

上述程式碼使用IronWord程式庫類的WordDocument構造方法讀取Word文件。

輸出

如何在C#中讀取具有格式的Word文件:圖7 - 從前面的程式碼到控制台輸出

說明

  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}");
        }
    }
}

在此我們使用WordDocument類獲取文件中的所有表格,然後遍歷它們並列印內容。

為現有文字新增樣式

我們可以使用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}");
        }
    }
}

在此我們建立一個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}");
        }
    }
}

在此我們建立新的Paragraph物件,並將樣式資訊新增到載入的Word文件中。

授權(免費試用可用)

獲取您的IronWord免費試用授權金鑰。 此金鑰需要放在appsettings.json中。

{
    "IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}
JSON

請提供您的電子郵件以獲取試用授權。 提交您的電子郵件ID後,金鑰將通過電子郵件傳遞給您。

如何在C#中讀取具有格式的Word文件:圖8 - 成功提交了試用表格

結論

IronWord 提供了一種便捷的方法來在C#中讀取具有格式的Word文件。 基於您的具體需求以及您正在處理的文件的復雜性擴展提供的程式碼。 本教學作為將IronWord整合到您的C#應用程式中用於Word文件處理的起點。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費現場演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲取您的無義務諮詢
完成以下表單或發郵件至sales@ironsoftware.com
您的詳細資訊將始終保持機密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立