跳過到頁腳內容
使用 IRONWORD

如何以 C# 將文件匯出至 Word

IronWord 讓 C# 開發人員可以使用簡單的程式碼將資料匯出到 Word 文件。 只需幾行程式碼,即可建立、填入和儲存包含文字、格式和複雜文件結構的 DOCX 檔案。

Microsoft Word 是一款廣泛用於建立和編輯文件的工具,以其多功能性和使用者友善的介面而聞名。 在軟體開發中,經常會遇到需要以程式設計方式產生 Word 文件的情況,無論是用於報告、文件編寫或資料展示。 無論您是建立自動化報告系統、生成發票、建立動態模板,還是從資料庫記錄產生批次文檔,將資料匯出為 Word 格式的功能都可以節省無數的手動工作時間。

在本指南中,我們將探討如何建立新的[C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)控制台應用程序,並使用[IronWord](/csharp/word/) (一個用於以程式設計方式操作 Word 文件的有效庫)將資料匯出到 C# 中的 MS Word 文件。 在本教學結束時,您將了解從專案設定到產生第一個包含自訂內容的 Word 文件的完整工作流程。

如何在 C# 中將文件匯出為 Word 文件?

  1. 建立一個新的 C# Visual Studio 專案。
  2. 安裝 C# Word 庫,以便將資料匯出到 Word。
  3. 導入 Word 庫的依賴項。
  4. 使用"new WordDocument (paragraph)"方法建立一個新的 Word 文件。
  5. 使用" SaveAs ()"函數儲存新建立的 Word 文件。

如何建立一個新的 C# 控制台應用程式?

若要在 Visual Studio 中建立新的 C# 控制台應用程序,請依照下列步驟操作。 控制台應用程式範本提供了一個簡單的起點,用於學習如何產生 Word 文檔,然後再將該功能整合到更大的應用程式(如 Web 服務或桌面軟體)中。

  1. 開啟 Visual Studio。 在啟動畫面上,選擇"建立新項目"。

Visual Studio 啟動畫面顯示"建立新專案"按鈕以高亮顯示,用於開始建立新的 C# 控制台應用程式。

  1. 選擇"控制台應用程式",然後按一下"下一步"。 如果出現多個選項,請選擇 C# 版本。

Visual Studio 中的專案範本選擇視窗顯示控制台應用程式範本選項,並套用了 C# 語言篩選器。

  1. 輸入項目名稱和地點。 按一下"下一步",選擇 .NET 6.0 或更高版本,然後按一下"建立"。

IronWord是什麼?我為什麼要使用它?

IronWord 是一個 .NET 函式庫,它提供了一個方便的 API,用於在 C# 中處理 Word 文件。 它允許開發人員建立 Word 文檔、修改現有文檔,並將其匯出到他們的 C# 應用程式中。 使用 IronWord,您可以根據來自各種來源(例如資料庫、API 或使用者輸入)的資料動態產生 Word 文件。 該程式庫處理所有複雜的底層 Office Open XML 規範,可讓您專注於業務邏輯,而不是文件格式的複雜性。

IronWord 為 Word 文件處理提供了許多優勢。 與某些需要在伺服器或開發機器上安裝 Microsoft Office 的替代方案不同,IronWord 可以獨立運行,因此非常適合雲端部署、容器化應用程式以及無法安裝 Office 的環境。 此庫支援多種文件元素,包括段落、表格、圖像、頁首、頁尾、樣式和格式選項,讓您可以完全控製文件的外觀和結構。

如何在我的專案中安裝 IronWord?

您可以使用 NuGet 套件管理器依照下列步驟輕鬆安裝 IronWord。 NuGet 是 .NET 的標準套件管理系統,讓程式庫的安裝和版本管理變得簡單可靠。

  1. 在 Visual Studio 中,開啟 NuGet 套件管理器窗口,然後前往"瀏覽"標籤。
  2. 在"瀏覽"標籤中,在搜尋列中輸入 IronWord,然後按 Enter 鍵。
  3. 將顯示包裹清單。 選擇最新軟體包,然後按一下"安裝"。

Visual Studio 中的 NuGet 套件管理器視窗顯示 IronWord 套件搜尋結果,其中"安裝"按鈕可見

安裝完成後,IronWord 即可使用。 安裝過程會自動處理所有相依性並正確配置您的項目參考。

如何使用 IronWord 將資料匯出到 Word 文件?

讓我們從使用 C# 中的 IronWord 將資料匯出到 Word 文件的實際範例開始。 以下程式碼片段示範了建立簡單 Word 文件的基本流程:

using IronWord;
using IronWord.Models;

System.Console.WriteLine("Enter the Text to export it to word document");
var userInput = System.Console.ReadLine();

// Create textRun which is a part of a paragraph content
Text textRun = new Text(userInput);
Paragraph paragraph = new Paragraph();
paragraph.AddChild(textRun);

// Create a new document object and add the paragraph to it
WordDocument doc = new WordDocument(paragraph);

// Export document to "document.docx" file
doc.SaveAs("document.docx");
using IronWord;
using IronWord.Models;

System.Console.WriteLine("Enter the Text to export it to word document");
var userInput = System.Console.ReadLine();

// Create textRun which is a part of a paragraph content
Text textRun = new Text(userInput);
Paragraph paragraph = new Paragraph();
paragraph.AddChild(textRun);

// Create a new document object and add the paragraph to it
WordDocument doc = new WordDocument(paragraph);

// Export document to "document.docx" file
doc.SaveAs("document.docx");
Imports IronWord
Imports IronWord.Models

System.Console.WriteLine("Enter the Text to export it to word document")
Dim userInput = System.Console.ReadLine()

' Create textRun which is a part of a paragraph content
Dim textRun As New Text(userInput)
Dim paragraph As New Paragraph()
paragraph.AddChild(textRun)

' Create a new document object and add the paragraph to it
Dim doc As New WordDocument(paragraph)

' Export document to "document.docx" file
doc.SaveAs("document.docx")
$vbLabelText   $csharpLabel

在這個例子中,我們將建立一個簡單的 Word 文檔,其中包含一個段落,內容為使用者提供的文字。 讓我們一步一步地分析程式碼: 1.導入所需庫:我們先從 IronWord 導入必要的命名空間。 IronWord 命名空間包含主要文檔類,而IronWord.Models提供內容模型類。 2.建立文字內容:我們建立一個Text對象,表示我們要包含在 Word 文件中的文字內容。 在這種情況下,它是從控制台收集的userInput 。 3.建立段落:接下來,我們建立一個Paragraph對象,並將Text物件( textRun )作為子元素添加到該段落對像中。 Word 文件中的一個段落通常包含一個或多個文字段,允許在單一段落中使用混合格式。 4.建立 Word 文件:我們實例化一個新的WordDocument對象,並將我們建立的段落作為參數傳遞。 這將使用指定的內容建立一個新的 Word 文件。 5.匯出文件:最後,我們呼叫WordDocument物件的SaveAs方法,將文件匯出為名為" document.docx "的 .docx 檔案。預設情況下,該檔案會保存在應用程式的工作目錄中。

本範例示範了使用 IronWord 將資料匯出到 Word 文件的基本工作流程。 您可以根據具體需求自訂現有 Word 文件的內容和結構。 例如,您可以新增多個段落、設定文字格式、插入表格、圖像、頁首、頁尾等等。

控制台輸出是什麼樣的?

控制台應用程式視窗顯示使用者文字輸入提示,並顯示正在處理以匯出 Word 文件的已輸入文字。

產生的 Word 文件是什麼樣子的?

Microsoft Word 文件視窗顯示產生的 DOCX 文件,匯出的文字內容顯示在文件正文中。

如何在 Word 文件中新增更複雜的內容?

雖然基本範例僅展示了簡單的文字匯出,但 IronWord 支援更複雜的文件建立。 以下範例示範如何新增包含多個段落和樣式的格式化文字:

using IronWord;
using IronWord.Models;

// Create a document with multiple formatted paragraphs
WordDocument doc = new WordDocument();

// Add a title paragraph with bold formatting
Paragraph titleParagraph = new Paragraph();
Text titleText = new Text("Sales Report Q4 2024");
titleText.Style = new TextStyle() { Bold = true, FontSize = 24 };
titleParagraph.AddChild(titleText);
doc.AddChild(titleParagraph);

// Add a regular paragraph with mixed formatting
Paragraph contentParagraph = new Paragraph();
Text normalText = new Text("Total revenue for Q4 was ");
Text emphasizedText = new Text("$1.2 million");
emphasizedText.Style = new TextStyle() { Bold = true, Italic = true };
Text endText = new Text(", exceeding projections by 15%.");

contentParagraph.AddChild(normalText);
contentParagraph.AddChild(emphasizedText);
contentParagraph.AddChild(endText);
doc.AddChild(contentParagraph);

// Save the formatted document
doc.SaveAs("quarterly_report.docx");
using IronWord;
using IronWord.Models;

// Create a document with multiple formatted paragraphs
WordDocument doc = new WordDocument();

// Add a title paragraph with bold formatting
Paragraph titleParagraph = new Paragraph();
Text titleText = new Text("Sales Report Q4 2024");
titleText.Style = new TextStyle() { Bold = true, FontSize = 24 };
titleParagraph.AddChild(titleText);
doc.AddChild(titleParagraph);

// Add a regular paragraph with mixed formatting
Paragraph contentParagraph = new Paragraph();
Text normalText = new Text("Total revenue for Q4 was ");
Text emphasizedText = new Text("$1.2 million");
emphasizedText.Style = new TextStyle() { Bold = true, Italic = true };
Text endText = new Text(", exceeding projections by 15%.");

contentParagraph.AddChild(normalText);
contentParagraph.AddChild(emphasizedText);
contentParagraph.AddChild(endText);
doc.AddChild(contentParagraph);

// Save the formatted document
doc.SaveAs("quarterly_report.docx");
Imports IronWord
Imports IronWord.Models

' Create a document with multiple formatted paragraphs
Dim doc As New WordDocument()

' Add a title paragraph with bold formatting
Dim titleParagraph As New Paragraph()
Dim titleText As New Text("Sales Report Q4 2024")
titleText.Style = New TextStyle() With {.Bold = True, .FontSize = 24}
titleParagraph.AddChild(titleText)
doc.AddChild(titleParagraph)

' Add a regular paragraph with mixed formatting
Dim contentParagraph As New Paragraph()
Dim normalText As New Text("Total revenue for Q4 was ")
Dim emphasizedText As New Text("$1.2 million")
emphasizedText.Style = New TextStyle() With {.Bold = True, .Italic = True}
Dim endText As New Text(", exceeding projections by 15%.")

contentParagraph.AddChild(normalText)
contentParagraph.AddChild(emphasizedText)
contentParagraph.AddChild(endText)
doc.AddChild(contentParagraph)

' Save the formatted document
doc.SaveAs("quarterly_report.docx")
$vbLabelText   $csharpLabel

本範例示範如何建立具有不同格式的文檔,使匯出的文檔更專業、更具視覺吸引力。 TextStyle類別提供了控製字型系列、大小、顏色、粗體、斜體、底線和其他文字屬性的屬性。

程式化匯出 Word 文件的常見用例有哪些?

了解實際應用程式有助於直觀地了解 Word 文件匯出功能如何為您的專案帶來好處。 以下幾個常見場景中,程式化文件產生功能都發揮了至關重要的作用:

發票和收據產生:從計費系統中自動建立包含抬頭、表格和付款條款的專業發票。

報告自動化:自動產生定期財務摘要、績效指標或合規性文件。

郵件合併操作:透過將資料庫記錄合併到範本中來建立個人化的合約、信件或證書。

文檔系統:將原始碼註解或資料庫模式轉換為格式化的技術文件。

表單處理:將網頁表單或調查回應轉換為格式化的 Word 文檔,供利害關係人審查。

有哪些關鍵要點?

總而言之,IronWord 提供了一個完整的解決方案,用於使用 C# 將資料匯出到 Word 文件。 無論您是產生簡單的報表、複雜的文件還是動態內容,IronWord 都能簡化流程,讓開發人員能夠以程式設計方式建立高品質的 Word 文件。 利用其特性和功能,您可以簡化文件產生工作流程,並向使用者提供專業文件。

該程式庫無需安裝 Microsoft Office,並且具有完整的 API 和可靠的效能,使其成為小型應用程式和企業級文件處理系統的理想選擇。 隨著您不斷探索 IronWord 的功能,您會發現許多方法來改善文件產生流程,並為使用者的文件需求提供更好的解決方案。

若要了解更多自動產生 Microsoft Word 文件的技巧,請造訪以下連結

常見問題解答

如何用 C# 將資料匯出至 Word 文件?

您可以使用 IronWord 在 C# 中將資料匯出至 Word 文件,方法是建立一個 C# 主控台應用程式,透過 NuGet 套件管理員安裝 IronWord,匯入必要的函式庫,並使用 API 以您的資料建立並儲存 Word 文件。

使用 .NET 函式庫建立 Word 文件有什麼好處?

使用 IronWord 之類的 .NET 函式庫來製作 Word 文件,可以讓開發人員以程式化的方式自動產生高品質的文件,使工作流程更有效率,並能適應特定的需求,而不需依賴 Microsoft Interop。

如何使用 C# 將文字格式化並將圖片加入 Word 文件?

使用 IronWord,您可以透過設定字型樣式、大小和顏色來格式化文字,並透過使用 API 將圖片插入文件來新增圖片。這可在 C# 應用程式中實現豐富的文件自訂功能。

IronWord 可以用於動態文件生成嗎?

是的,IronWord 可讓您根據資料庫或使用者輸入等各種來源的資料來建立 Word 文件,以滿足使用者的特定需求,進而實現動態文件生成。

使用 IronWord 創建 Word 文檔有哪些步驟?

要使用 IronWord 創建 Word 文檔,首先要建立 C# Console Application,透過 NuGet 安裝 IronWord,匯入函式庫,建立文字和段落物件,並使用 SaveAs 方法匯出文檔。

IronWord 如何簡化以 C# 語言建立 Word 文件的工作?

IronWord 透過提供直接的 API 簡化了 Word 文件的建立,讓開發人員可以輕鬆地以程式化的方式建立、處理和匯出 Word 文件,進而降低複雜度並提昇生產力。

是否可以用 C# 從使用者輸入建立 Word 文件?

是的,使用 IronWord,您可以透過擷取使用者輸入、建立 Text 物件、將其加入段落,然後再使用 IronWord API 將其匯出為 .docx 檔案,從而建立 Word 文件。

C# 匯出至 Word 時,如何排除常見問題?

在排除使用 IronWord 匯出至 Word 的問題時,請確保已匯入所有必要的函式庫,透過 NuGet 安裝了正確版本的函式庫,並且您的資料類型與所使用的 API 方法相容。

程式化產生 Word 文件有哪些實際應用?

使用 IronWord 程式化產生 Word 文件對於建立自動化報告、文件和資料呈現文件非常有用,尤其是在處理大型資料集或頻繁更新的資訊時。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。