跳至頁尾內容
使用 IRONXL

C# DataGridView 匯出到 Excel 並帶格式:完整指南

C# DataGridView Export to Excel with Formatting:完整指南:圖 1 - C# DataGridView Export to Excel with Formatting

DataGridView 資料匯出至 Excel 檔案是 Windows Forms 應用程式的常見需求。 無論是產生報表或傳輸資料進行分析,開發人員都需要一個可靠的方法來匯出 DataGridView 的內容,同時保留格式。 在這篇文章中,我們將教您如何使用 IronXL 將 DataGridView 匯出至 Excel,這是一種現代化的方法,不需要安裝 Microsoft Excel 即可完美運作。

!{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110--

如何為 DataGridView 匯出設定 Windows 表單專案? 傳統的方法需要透過 COM 標籤加入 Microsoft Excel 物件庫的參照。 然而,此方法有顯著的缺點:需要在每台機器上安裝 Microsoft Excel、涉及使用 `private void releaseobject` 方法釋放物件的複雜模式,以及在處理大型 Excel 檔案時表現不佳。 IronXL 完全消除了這些問題。 在 Visual Studio 中,只需透過 NuGet Package Manager 進行安裝,無需選擇"新增參考"功能表或瀏覽 COM 索引標籤。 該資料庫可處理所有資料匯出作業,而不需依賴 Microsoft Office。 要開始使用,請在 Visual Studio 中建立一個新的 Windows Forms 專案,然後將下列命名空間新增至您的表單: ```cs using IronXL; using System.Data; ``` 在您的表單中加入 `DataGridView` 控件和 Button。 `DataGridView` 控件會在匯出前顯示資料,而按鈕則會觸發匯出 `DataGridView` 作業。

如何將資料載入 DataGridView 控件? 表單載入事件非常適用於將資料填充到您的 `DataGridView` 中。 以下程式碼範例示範將 `DataTable` 綁定至 `DataGridView` 控件: ```cs private void Form1_Load(object sender, EventArgs e) { // Create DataTable with sample data DataTable dt = new DataTable(); dt.Columns.Add("ProductID", typeof(int)); dt.Columns.Add("ProductName", typeof(string)); dt.Columns.Add("Price", typeof(decimal)); dt.Columns.Add("Stock", typeof(int)); // Add rows with values dt.Rows.Add(1, "Laptop", 999.99, 50); dt.Rows.Add(2, "Mouse", 29.99, 200); dt.Rows.Add(3, "Keyboard", 79.99, 150); dt.Rows.Add(4, "Monitor", 349.99, 75); dataGridView1.DataSource = dt; } ``` ### 填充式資料庫 ![C# DataGridView Export to Excel with Formatting:完整指南:圖片 2 - 我們表單的 UI](/static-assets/excel/blog/datgridview-excel/datgridview-excel-2.webp) 這段程式碼建立了一個有四列的 `DataTable dt`,然後使用 Add 方法以範例值填充 `DataGridView` 行。 `DataGridView` 控件接受 `DataTable` 作為其資料來源,這將以表格格式顯示資料。 第一列包含整數 ID,其他列則包含字串和十進位值。

如何將 DataGridView 資料匯出至 Excel 檔案? 按鈕按一下事件處理器包含核心匯出邏輯。 IronXL 的方法有別於傳統方法; `DataGridView` 的內容可透過 `DataTable` 的中間步驟直接匯出至 Excel 檔案: ```cs private void btnExport_Click(object sender, EventArgs e) { try { // Convert DataGridView to DataTable DataTable dt = new DataTable(); foreach (DataGridViewColumn column in dataGridView1.Columns) dt.Columns.Add(column.HeaderText); foreach (DataGridViewRow row in dataGridView1.Rows) { if (!row.IsNewRow) { DataRow dataRow = dt.NewRow(); for (int i = 0; i < dataGridView1.Columns.Count; i++) dataRow[i] = row.Cells[i].Value; dt.Rows.Add(dataRow); } } // Create workbook and export WorkBook workbook = WorkBook.Create(); WorkSheet worksheet = workbook.DefaultWorkSheet; worksheet.LoadFromDataTable(dt, true); workbook.SaveAs("C:\\Reports\\Export.xlsx"); MessageBox.Show("Export complete!"); } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } } ``` ### DataGridView 至 Excel 輸出。 ![C# DataGridView Export to Excel with Formatting:完整指南:圖片 3 - 生成的 Excel 檔案](/static-assets/excel/blog/datgridview-excel/datgridview-excel-3.webp) 此按鈕點選事件處理器具有 `object sender, EventArgs e` 參數,它會遍歷 `DataGridView` 行和列中的所有資料,建立一個 `DataTable` 。 `LoadFromDataTable` 方法接受 `DataTable` 並填充工作表。 然後將工作簿物件儲存至指定位置。 IronXL.Excel 也能有效率地輸出大型 Excel 檔案,而不會產生 Microsoft Interop 常見的記憶體問題。

如何在匯出的 Excel 檔案中套用格式化? 建立格式化的 Excel 檔案需要為標頭行和儲存格設計樣式。 本範例示範套用標題行背景顏色和交替行造型: ```cs private void ExportWithFormatting(object sender, EventArgs e) { WorkBook workbook = WorkBook.Create(); WorkSheet worksheet = workbook.DefaultWorkSheet; // Add header row string[] headers = { "ID", "Name", "Price", "Stock" }; for (int col = 0; col < headers.Length; col++) { worksheet.SetCellValue(0, col, headers[col]); worksheet[$"{(char)('A' + col)}1"].Style.Font.Bold = true; worksheet[$"{(char)('A' + col)}1"].Style.SetBackgroundColor("#4472C4"); } // Add data with alternating row colors int rowIndex = 1; foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.IsNewRow) continue; for (int col = 0; col < dataGridView1.Columns.Count; col++) { worksheet.SetCellValue(rowIndex, col, row.Cells[col].Value?.ToString()); } // Apply alternating background colors if (rowIndex % 2 == 0) { var range = worksheet[$"A{rowIndex + 1}:D{rowIndex + 1}"]; range.Style.SetBackgroundColor("#D6DCE5"); } rowIndex++; } workbook.SaveAs("C:\\Reports\\FormattedExport.xlsx"); } ``` ### 格式化的 Excel 檔案輸出 ![C# DataGridView Export to Excel with Formatting:完整指南:圖片 4 - 生成格式化 Excel 檔案的輸出](/static-assets/excel/blog/datgridview-excel/datgridview-excel-4.webp)。 此 C# `DataGridView` 匯出至 Excel 的格式化範例將設定第一行為具有粗體字型和背景顏色的樣式化標頭行。 程式碼應用交替行的樣式,以提高可讀性。 您可以使用 IronXL 全面的 [樣式 API](/csharp/excel/how-to/cell-font-size/) 自訂具有不同字體樣式、填充樣式和邊框配置的儲存格。 ## 結論 有了 IronXL.Excel,在 Windows Forms 應用程式中將 `DataGridView` 匯出至 Excel 就變得簡單直接。 IronXL.Excel 與傳統 Microsoft Excel 物件庫方法不同,需要 COM 標籤參照和複雜的物件清理程式碼,IronXL.Excel 提供簡潔、現代化的 API,用於建立具有格式化功能的 Excel 檔案。 該函式庫可處理從基本資料匯出至 Excel,到複雜的格式化 Excel 檔案產生等各種功能,包括標題行背景顏色造型和交替行。 對於處理大型 Excel 檔案的應用程式,IronXL.Excel 可提供優異的效能,而無需安裝 Microsoft Excel。 準備好簡化您的 `DataGridView` 到 Excel 的工作流程了嗎? [立即開始免費試用](trial-license),或探索[生產部署的 IronXL 授權選項](/csharp/excel/licensing/)。

常見問題解答

如何使用 C# 將 DataGridView 資料匯出到 Excel?

使用 IronXL,您可以利用其強大的資料操作和匯出功能,輕鬆地將 DataGridView 資料匯出到 C# 中的 Excel 檔案。

將 DataGridView 匯出到 Excel 時有哪些格式設定選項?

IronXL 可讓您在將 DataGridView 匯出到 Excel 時套用各種格式設定選項,例如標題樣式和交替行顏色。

是否可以將Windows Forms應用程式中的DataGridView資料匯出到Excel?

是的,您可以使用 IronXL 在 Windows Forms 應用程式中將 DataGridView 資料匯出到 Excel,IronXL 為此提供了無縫整合和功能。

將 DataGridView 匯出到 Excel 時,可以設定標題樣式嗎?

IronXL 可讓您在將 DataGridView 資料匯出至 Excel 時,使用自訂字體、顏色和其他格式選項來設定標題樣式。

從 DataGridView 匯出資料時,如何在 Excel 中套用交替行顏色?

IronXL 可讓您在從 DataGridView 匯出資料時,對 Excel 工作表套用交替的行顏色,從而增強資料的視覺吸引力和可讀性。

我是否需要特殊的庫才能在 C# 中將 DataGridView 匯出到 Excel?

是的,使用像 IronXL 這樣的函式庫可以簡化在 C# 中將 DataGridView 匯出到 Excel 的過程,並提供強大的資料處理和格式化工具。

使用 IronXL 將 DataGridView 匯出到 Excel 有哪些好處?

IronXL 具有易於使用、格式設定選項全面、相容 Windows Forms 等優點,使其成為將 DataGridView 匯出到 Excel 的理想選擇。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。