跳至頁尾內容
USING IRONXL
如何在C#中將DataGridView匯出到Excel

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

本教程提供了如何在Windows Forms應用程式中使用IronXL程式庫將DataGridView控制項中的資料匯出到Excel檔案的綜合指南。 我們的重點將放在為想要將Microsoft Excel功能整合到其C#專案中的初學者創造無縫的體驗。

How to Export DataGridView to Excel in C

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

開始使用IronXL

IronXL是一個強大的程式庫,可簡化在.NET Framework應用程式中處理Excel文件的過程。 它允許您匯出大型Excel檔案,處理複雜的資料來源,並提供對.NET Excel檔案操作的廣泛支援,而無需擁有Microsoft Excel物件庫。 讓我們設置專案。

設置您的專案

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

打開Visual Studio並建立一個新的Windows Forms應用程式。 這將是我們專案的基礎,我們將在這裡實現將DataGridView資料匯出到Excel檔案的功能。

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

2. 安裝IronXL

IronXL可以輕鬆地新增到您的專案中。 在Visual Studio中,導航到'管理NuGet套件'選項,搜尋IronXL並安裝它。 此操作將處理所有需要的依賴項,以便在C#中將DataGridView匯出到Excel。

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

3. 準備使用者介面

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

實現匯出功能

在本節中,我們將教您如何編程,實現從Windows Forms應用程式中的DataGridView匯出資料到Excel文件的功能,並使用IronXL。

構建應用程式

首先,您需要將DataGridView控制項新增到您的表單。 這個控制項是您資料顯示在匯出之前的主要組件。 您可以通過在Visual Studio的工具箱中拖動一個DataGridView到您的表單上輕鬆新增它。 我們還可以新增一個按鈕來將DataGridView資料匯出到Excel檔案。

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

下一步是將資料載入到DataGridView中。 這些資料可以來自多種來源,例如DataSet。 如果您剛開始,您可能想要程式化地建立一個新的DataTable,並用範例資料填充,以查看它的工作原理。 或者,您可以從外部來源匯入資料。 這裡的關鍵是將您的資料來源綁定到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 Form中的一個按鈕。 此按鈕在被點擊時會啟動匯出過程。 以下是如何設置此互動:

  • 在您的Windows Form中,應該有一個專門用於匯出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工作表中的相應單元格中。 這是通過使用索引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程式庫在C#中將DataGridView中的資料匯出到Excel文件。這涉及建立Windows Forms項目,通過NuGet安裝IronXL,以及實作將資料從DataGridView轉移到Excel工作表的邏輯。

設置DataGridView以匯出到Excel涉及哪些步驟?

步驟包括在Windows Forms項目中建立DataGridView,將其綁定到資料來源,向表單新增按鈕,並使用IronXL程式庫在按鈕的點擊事件處理程式中編寫匯出邏輯。

如何在Visual Studio項目中安裝IronXL?

要在Visual Studio項目中安裝IronXL,導航到「管理NuGet套件」,搜索IronXL並安裝它來處理所有必要的依賴項,以便將DataGridView匯出到Excel。

我可以使用IronXL匯出大型Excel文件嗎?

是的,IronXL允許匯出大型Excel文件,提供強大功能來處理大量資料集,而無需使用Microsoft Excel Object Library。

DataGridView匯出教程中按鈕的角色是什麼?

教程中的按鈕觸發匯出過程。在點擊時,它執行將資料從DataGridView轉移到Excel文件的邏輯,使用IronXL程式庫。

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

IronXL通過遍歷DataGridView的行和列來便捷進行資料傳輸,將每個單元格的資料複製到相應的Excel工作表單元格中。

如何在匯出過程中使用IronXL管理錯誤?

您可以通過將您的匯出邏輯包裹在try-catch塊中來捕獲和處理異常,確保即使在發生文件存取權限等問題時也能夠順利運行。

如何在將DataGridView資料匯出後保存Excel文件?

使用IronXL將資料轉移到Excel工作表後,您可以使用IronXL的SaveAs方法將文件保存到系統中。

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

是的,IronXL提供免費試用,允許使用者探索其在.NET應用程式中處理Excel文件的功能。還提供授權供進一步開發。

Curtis Chau
技術作家

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

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話