使用IRONXL

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

發佈 2024年1月27日
分享:

本教程提供了有關如何從中導出數據的全面指南 DataGridView 控制項 在 Windows Forms 應用程式中使用將資料匯出到 Excel 檔案 IronXL 在 C# 中的資料庫。我們將重點放在為初學者創建無縫體驗,讓他們將 Microsoft Excel 功能整合到 C# 項目中。

如何將 DataGridView 匯出到 Excel 在 C

  1. 在 Visual Studio 中建立一個 C# Windows Forms 專案。

  2. 使用 NuGet 套件管理器安裝 Excel 庫。

  3. 在 Windows Form UI 中建立一個 DataGridView 和一個按鈕。

  4. 將資料來源附加到 DataGridView。

  5. 在按鈕的點擊事件處理程序中應用資料匯出邏輯。

開始使用 IronXL

IronXL 是一個強大的庫,可以簡化在 .NET Framework 應用程式中處理 Excel 文件的過程。它允許您導出大型 Excel 文件,處理複雜的數據源,並且在不需要 Microsoft Excel Object Library 的情況下,為 .NET 的 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,然後安裝它。此操作將處理將 DataGridView 導出到 C# 中的 Excel 所需的所有依賴項。

如何在C#中將DataGridView導出到Excel:圖2 - 通過NuGet包管理器安裝IronXL庫

3. 準備使用者介面

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

實現匯出功能

在本節中,我們將教您如何程式設計功能,讓您能夠在 Windows Forms 應用程式中從 DataGridView 匯出數據到 Excel 文件,使用 IronXL。

構建應用程式

首先,你需要在表單中添加一個 DataGridView 控制項。這個控制項是顯示數據的主要組件,在數據導出之前會顯示在這裡。你可以通過從 Visual Studio 工具箱中拖動 DataGridView 到表單上來輕鬆添加它。我們還可以添加一個按鈕,用於將 DataGridView 資料導出到 Excel 文件。

如何將 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
VB   C#

處理按鈕點擊事件

我們與用戶的主要交互點將是 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
VB   C#

從 DataGridView 匯出資料

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

using IronXL;
using IronXL;
Imports IronXL
VB   C#

在事件處理程序中,首先要使用 IronXL 初始化一個新的工作簿和工作表。這是我們將從 DataGridView 轉移數據的地方。

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

在這裡,我們創建一個工作簿,然後添加一個工作表。工作表命名為“ExportedData”,但是你可以根據你的應用程式的上下文選擇任何名字。

WorkBook workbook = new WorkBook();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
WorkBook workbook = new WorkBook();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
Dim workbook As New WorkBook()
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("ExportedData")
VB   C#

填充 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
VB   C#

要將行和列索引轉換為 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
VB   C#

儲存 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)
VB   C#

錯誤處理

在任何數據導出過程中,處理異常對於確保應用程式的穩定性至關重要。將導出邏輯包裹在 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
VB   C#

輸出

當我們運行程式時,這個介面將會顯示出來:

如何將 DataGridView 匯出到 Excel 中的 C#:圖 4 - 先前代碼的輸出表單

您可以在這裡看到資料顯示在DataGridView中。現在,點擊“匯出”按鈕。這將把DataGridView中的資料匯出到Excel檔案。

如何將DataGridView匯出到Excel中:圖5 - 匯出成功消息

在這裡,你可以看到彈出了一個訊息框,並且數據已經導出到 Excel 文件。以下是生成的 Excel 文件:

如何在 C# 中將 DataGridView 匯出到 Excel:圖 6 - 從匯出前一個表單產生的 Excel 檔案

結論

通過遵循本指南,您現在擁有一個基本且強大的工具,可以使用 C# 將 DataGridView 數據導出到 Excel 文件。 IronXL. 這項功能對於需要數據分析、報告或只是不同格式之間數據傳輸的應用程式至關重要。記住,嘗試 DataGridView 控制項和 IronXL 庫的不同功能,可以實現更多自定義和高級的實現。

IronXL 提供了一個 免費試用 你可以用來探索其功能的內容。授權費用從$749起,對於尋求可靠且有效解決方案的專業人士和組織來說,這是一項值得的投資,用於在.NET應用程序中操作Excel文件。

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

< 上一頁
如何在C#控制台應用程式中讀取Excel檔案
下一個 >
如何從 CSV 檔案讀取資料並將其存儲在資料庫 C#

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,023,839 查看許可證 >