跳過到頁腳內容
使用 IRONXL
如何在 C# 中將 DataGridView 匯出至 Excel

如何在 C# 中將 Datagridview 導出到 Excel

本教學課程全面介紹如何使用 C# 中的IronXL函式庫將 Windows 窗體應用程式中的DataGridView控制項中的資料匯出到 Excel 檔案。 我們將致力於為希望將 Microsoft Excel 功能整合到 C# 專案中的初學者創造無縫體驗。

如何在 C# 中將 DataGridView 匯出到 Excel

  1. 在 Visual Studio 中建立一個 C# Windows Forms 專案。
  2. 使用 NuGet 套件管理器安裝 Excel 庫。
  3. 在 Windows 窗體 UI 中建立一個 DataGridView 和一個按鈕。
  4. 將資料來源附加到 DataGridView。
  5. 在按鈕的點擊事件處理程序中套用資料匯出邏輯。

IronXL入門指南

IronXL 是一個強大的程式庫,可以簡化在 .NET Framework 應用程式中處理 Excel 文件的過程。 它允許您匯出大型 Excel 文件、處理複雜的資料來源,並為 .NET Excel 文件操作提供廣泛的支持,而無需 Microsoft Excel 物件庫。 讓我們開始設定項目。

設定您的項目

1. 建立一個新的 Windows 窗體應用程式

開啟 Visual Studio 並建立一個新的 Windows 窗體應用程式。 這將是我們專案的基礎,我們將在此基礎上實作將 DataGridView 資料匯出到 Excel 檔案的功能。

如何在 C# 中將 DataGridView 匯出到 Excel:圖 1 - 在 Visual Studio 中建立新的 Windows 窗體應用程式

2. 安裝 IronXL

IronXL 可以輕鬆添加到您的專案中。 在 Visual Studio 中,導覽至"管理 NuGet 套件"選項,搜尋 IronXL,然後安裝它。 此操作將處理將 DataGridView 匯出到 Excel 所需的所有依賴項(C#)。

如何在 C# 中將 DataGridView 匯出到 Excel:圖 2 - 透過 NuGet 套件管理器安裝 IronXL 庫

3. 準備使用者介面

在表單中新增一個 DataGridView 控制項。 此控制項將保存我們打算匯出的資料。 此外,新增一個按鈕來觸發匯出過程。 您可以將其標記為"匯出到 Excel"或類似名稱。

實現導出功能

在本節中,我們將詳細說明如何使用 IronXL 編寫程序,實作將 Windows Forms 應用程式中的 DataGridView 中的資料匯出到 Excel 文件的功能。

建立應用程式

首先,您需要在表單中新增一個 DataGridView 控制項。 此控制項是資料匯出前顯示的主要元件。 您可以透過將 DataGridView 從 Visual Studio 的工具箱拖曳到窗體上輕鬆新增它。 我們也可以新增一個按鈕,將 DataGridView 資料匯出到 Excel 檔案。

如何在 C# 中將 DataGridView 匯出到 Excel:圖 3 - 新增一個按鈕以將 DataGridView 資料匯出到 Excel 文件

下一步是將資料載入到 DataGridView 中。 這些數據可以來自各種來源,例如DataTableDataSet 。 如果你是新手,你可能需要透過程式設計建立一個新的DataSetDataTable ,並用範例資料填充它,看看它是如何運作的。 或者,您可以從外部來源匯入資料。 關鍵在於將資料來源綁定到 DataGridView,這樣就能有效地將資料連結到網格。 將資料綁定到 DataGridView 後,您將在表單的網格中看到它。

private void BindDataToDataGridView()
{
    // Create a new DataTable.
    DataTable dataTable = new DataTable();
    // Define columns for the DataTable.
    dataTable.Columns.Add("Employee ID", typeof(int));
    dataTable.Columns.Add("Name", typeof(string));
    dataTable.Columns.Add("Department", typeof(string));
    dataTable.Columns.Add("Joining Date", typeof(DateTime));
    // Add sample data to the DataTable.
    for (int i = 1; i <= 25; i++)
    {
        dataTable.Rows.Add(i, "Employee " + i, "Department " + (i % 5 + 1), DateTime.Now.AddDays(-i * 15));
    }
    // Bind the DataTable to the DataGridView.
    dataGridView1.DataSource = dataTable;
}
private void BindDataToDataGridView()
{
    // Create a new DataTable.
    DataTable dataTable = new DataTable();
    // Define columns for the DataTable.
    dataTable.Columns.Add("Employee ID", typeof(int));
    dataTable.Columns.Add("Name", typeof(string));
    dataTable.Columns.Add("Department", typeof(string));
    dataTable.Columns.Add("Joining Date", typeof(DateTime));
    // Add sample data to the DataTable.
    for (int i = 1; i <= 25; i++)
    {
        dataTable.Rows.Add(i, "Employee " + i, "Department " + (i % 5 + 1), DateTime.Now.AddDays(-i * 15));
    }
    // Bind the DataTable to the DataGridView.
    dataGridView1.DataSource = dataTable;
}
Private Sub BindDataToDataGridView()
	' Create a new DataTable.
	Dim dataTable As New DataTable()
	' Define columns for the DataTable.
	dataTable.Columns.Add("Employee ID", GetType(Integer))
	dataTable.Columns.Add("Name", GetType(String))
	dataTable.Columns.Add("Department", GetType(String))
	dataTable.Columns.Add("Joining Date", GetType(DateTime))
	' Add sample data to the DataTable.
	For i As Integer = 1 To 25
		dataTable.Rows.Add(i, "Employee " & i, "Department " & (i Mod 5 + 1), DateTime.Now.AddDays(-i * 15))
	Next i
	' Bind the DataTable to the DataGridView.
	dataGridView1.DataSource = dataTable
End Sub
$vbLabelText   $csharpLabel

處理按鈕點擊事件

我們與使用者的主要互動點將是 Windows 窗體中的一個按鈕。 點擊此按鈕即可啟動匯出程序。 以下是如何設定此互動的方法:

  • 在您的 Windows 表單中,應該有一個專門用於匯出 DataGridView 資料的按鈕。
  • 此按鈕在您的 C# 程式碼中具有事件處理方法。 當使用者點擊按鈕時,此方法將被觸發。
private void btnExport_Click(object sender, EventArgs e)
{
    // Code to export data will go here
}
private void btnExport_Click(object sender, EventArgs e)
{
    // Code to export data will go here
}
Private Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Code to export data will go here
End Sub
$vbLabelText   $csharpLabel

從 DataGridView 匯出數據

要匯出 DataGridView 數據,我們需要先引用 IronXL 命名空間:

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

在事件處理程序中,第一步是使用 IronXL 初始化一個新的工作簿和工作表。 這裡將傳輸來自 DataGridView 的資料。

  • WorkBook物件代表整個 Excel 檔案。 工作簿中的WorkSheet就像 Excel 文件中的單一頁面或標籤頁。

在這裡,我們建立一個工作簿,然後在其中新增一個工作表。 工作表名為"ExportedData",但您可以根據應用程式的上下文選擇任何適當的名稱。

WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
Dim workbook As WorkBook = WorkBook.Create()
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("ExportedData")
$vbLabelText   $csharpLabel

填充 Excel 表格

下一步是遍歷 DataGridView 的行和列,並將每個儲存格的資料複製到 Excel 工作表中的對應儲存格。

  • 外層循環遍歷每一行,而內層循環遍歷對應行中的每一列。
  • 我們將 DataGridView 中每個儲存格的值賦給 Excel 工作表中對應的儲存格。 這是透過索引i (行)和j (列)來實現的。
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        // Convert row and column index to Excel cell address format
        string cellAddress = ConvertToCellAddress(i, j);
        worksheet[cellAddress].Value = dataGridView1.Rows[i].Cells[j].Value.ToString();
    }
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        // Convert row and column index to Excel cell address format
        string cellAddress = ConvertToCellAddress(i, j);
        worksheet[cellAddress].Value = dataGridView1.Rows[i].Cells[j].Value.ToString();
    }
}
For i As Integer = 0 To dataGridView1.Rows.Count - 1
	For j As Integer = 0 To dataGridView1.Columns.Count - 1
		' Convert row and column index to Excel cell address format
		Dim cellAddress As String = ConvertToCellAddress(i, j)
		worksheet(cellAddress).Value = dataGridView1.Rows(i).Cells(j).Value.ToString()
	Next j
Next i
$vbLabelText   $csharpLabel

若要將行索引和列索引轉換為 Excel 儲存格位址,可以使用下列輔助方法:

private string ConvertToCellAddress(int row, int column)
{
    // Columns in Excel are labeled as A, B, C, ..., Z, AA, AB, ..., etc.
    // The following code converts a column index to this format.
    string columnLabel = "";
    while (column >= 0)
    {
        columnLabel = (char)('A' + column % 26) + columnLabel;
        column = column / 26 - 1;
    }
    // Rows in Excel are labeled as 1, 2, 3, ..., n
    // Adding 1 because Excel is 1-based and our loop is 0-based.
    string rowLabel = (row + 1).ToString();
    return columnLabel + rowLabel;
}
private string ConvertToCellAddress(int row, int column)
{
    // Columns in Excel are labeled as A, B, C, ..., Z, AA, AB, ..., etc.
    // The following code converts a column index to this format.
    string columnLabel = "";
    while (column >= 0)
    {
        columnLabel = (char)('A' + column % 26) + columnLabel;
        column = column / 26 - 1;
    }
    // Rows in Excel are labeled as 1, 2, 3, ..., n
    // Adding 1 because Excel is 1-based and our loop is 0-based.
    string rowLabel = (row + 1).ToString();
    return columnLabel + rowLabel;
}
Private Function ConvertToCellAddress(ByVal row As Integer, ByVal column As Integer) As String
	' Columns in Excel are labeled as A, B, C, ..., Z, AA, AB, ..., etc.
	' The following code converts a column index to this format.
	Dim columnLabel As String = ""
	Do While column >= 0
		columnLabel = ChrW(AscW("A"c) + column Mod 26) & columnLabel
		column = column \ 26 - 1
	Loop
	' Rows in Excel are labeled as 1, 2, 3, ..., n
	' Adding 1 because Excel is 1-based and our loop is 0-based.
	Dim rowLabel As String = (row + 1).ToString()
	Return columnLabel & rowLabel
End Function
$vbLabelText   $csharpLabel

儲存 Excel 文件

所有資料傳輸完成後,下一步是將此工作簿另存為 Excel 檔案。此步驟會在您系統中的指定路徑建立一個 Excel 檔案。

workbook.SaveAs("DataGridViewExport.xlsx");
MessageBox.Show("Data exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
workbook.SaveAs("DataGridViewExport.xlsx");
MessageBox.Show("Data exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
workbook.SaveAs("DataGridViewExport.xlsx")
MessageBox.Show("Data exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
$vbLabelText   $csharpLabel

錯誤處理

在任何資料匯出過程中,處理異常情況對於確保應用程式的穩定性至關重要。 將匯出邏輯包裝在 try-catch 區塊中,可確保在匯出過程中出現的任何問題(如檔案存取權限、資料格式問題等)都能被擷取並妥善處理。

try
{
    // Export logic
}
catch (Exception ex)
{
    MessageBox.Show("An exception occurred: " + ex.Message);
}
try
{
    // Export logic
}
catch (Exception ex)
{
    MessageBox.Show("An exception occurred: " + ex.Message);
}
Try
	' Export logic
Catch ex As Exception
	MessageBox.Show("An exception occurred: " & ex.Message)
End Try
$vbLabelText   $csharpLabel

輸出

程式運行後,將顯示以下介面:

如何在 C# 中將 DataGridView 匯出到 Excel:圖 4 - 先前程式碼的輸出形式

您可以看到,數據顯示在 DataGridView 中。 現在,點擊"匯出"按鈕。 它會將 DataGridView 中的資料匯出到 Excel 檔案。

如何在 C# 中將 DataGridView 匯出到 Excel:圖 5 - 匯出成功訊息

您可以看到此處彈出了一個訊息框,資料已匯出到 Excel 檔案。以下是輸出的 Excel 檔案:

如何在 C# 中將 DataGridView 匯出到 Excel:圖 6 - 匯出上一個窗體後的輸出 Excel 文件

結論

透過遵循本指南,您現在擁有一個基本但功能強大的工具,可以使用 C# 和IronXL將 DataGridView 資料匯出到 Excel 檔案。 對於需要資料分析、報告或在不同格式之間傳輸資料的應用程式來說,此功能至關重要。 請記住,嘗試使用 DataGridView 控制項和 IronXL 庫的不同功能可以實現更客製化和更高級的實作。

IronXL 提供免費試用版,您可以利用該試用版來體驗其各項功能。 授權價格從 $liteLicense 起,對於尋求在 .NET 應用程式中進行 Excel 文件操作的可靠高效解決方案的專業人士和組織來說,這是一筆值得的投資。

你的旅程並未就此結束。 繼續探索 IronXL 的更多功能以及其他增強 Windows Forms 應用程式的方法。 祝您編碼愉快!

常見問題解答

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

您可以使用 IronXL.Excel 函式庫在 C# 中將 DataGridView 中的資料匯出至 Excel 檔案。這需要建立一個 Windows Forms 專案,透過 NuGet 安裝 IronXL,並實作邏輯,將資料從 DataGridView 傳輸至 Excel 工作表。

設定 DataGridView 匯出至 Excel 時需要哪些步驟?

步驟包括在 Windows 窗體專案中建立 DataGridView、將 DataGridView 與資料來源綁定、在窗體中加入按鈕,以及使用 IronXL 函式庫在按鈕的點選事件處理器中撰寫匯出邏輯。

如何在 Visual Studio 專案中安裝 IronXL?

若要在 Visual Studio 專案中安裝 IronXL,請導航至「管理 NuGet 套件」,搜尋 IronXL,然後安裝它以處理將 DataGridView 匯出至 Excel 的所有必要相依性。

我可以使用 IronXL 匯出大型 Excel 檔案嗎?

是的,IronXL.Excel 允許匯出大型 Excel 檔案,提供處理大量資料集的強大功能,而不需要 Microsoft Excel 物件庫。

DataGridView 匯出教學中按鈕的作用是什麼?

教學中的按鈕會觸發匯出程序。點擊後,它會執行邏輯,使用 IronXL.Excel 函式庫將資料從 DataGridView 傳輸至 Excel 檔案。

IronXL 如何處理從 DataGridView 到 Excel 的資料傳輸?

IronXL 透過遍歷 DataGridView 的行和列,並將每個單元格的資料複製到對應的 Excel 工作表單元格中,從而促進資料傳輸。

如何管理 IronXL 匯出過程中的錯誤?

您可以透過將您的匯出邏輯包裝在 try-catch 區塊中來管理錯誤,以捕捉並處理異常,即使發生檔案存取權限等問題,也能確保順暢運作。

從 DataGridView 匯出資料後,如何儲存 Excel 檔案?

使用 IronXL 將資料傳輸至 Excel 工作表後,您可以使用 IronXL 的 SaveAs 方法將檔案儲存至您的系統。

是否提供 IronXL 免費試用版以測試其功能?

是的,IronXL 提供免費試用,讓使用者探索其在 .NET 應用程式中操作 Excel 檔案的功能。可取得授權以進一步開發。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。