如何在 C# 中將 DataGridView 匯出到 Excel
本教學課程全面介紹如何使用 C# 中的IronXL函式庫將 Windows 窗體應用程式中的DataGridView控制項中的資料匯出到 Excel 檔案。 我們將致力於為希望將 Microsoft Excel 功能整合到 C# 專案中的初學者創造無縫體驗。
如何在 C# 中將 DataGridView 匯出到 Excel
- 在 Visual Studio 中建立一個 C# Windows Forms 專案。
- 使用 NuGet 套件管理器安裝 Excel 庫。
- 在 Windows 窗體 UI 中建立一個 DataGridView 和一個按鈕。
- 將資料來源附加到 DataGridView。
- 在按鈕的點擊事件處理程序中套用資料匯出邏輯。
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 中。 這些數據可以來自各種來源,例如DataTable或DataSet 。 如果你是新手,你可能需要透過程式設計建立一個新的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;
}處理按鈕點擊事件
我們與使用者的主要互動點將是 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
}從 DataGridView 匯出數據
要匯出 DataGridView 數據,我們需要先引用 IronXL 命名空間:
using IronXL;using IronXL;在事件處理程序中,第一步是使用 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");填充 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();
}
}若要將行索引和列索引轉換為 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;
}儲存 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);錯誤處理
在任何資料匯出過程中,處理異常情況對於確保應用程式的穩定性至關重要。 將匯出邏輯包裝在 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);
}輸出
程式運行後,將顯示以下介面:
如何在 C# 中將 DataGridView 匯出到 Excel:圖 4 - 先前程式碼的輸出形式
您可以看到,數據顯示在 DataGridView 中。 現在,點擊"匯出"按鈕。 它會將 DataGridView 中的資料匯出到 Excel 檔案。
如何在 C# 中將 DataGridView 匯出到 Excel:圖 5 - 匯出成功訊息
您可以看到此處彈出了一個訊息框,資料已匯出到 Excel 檔案。以下是輸出的 Excel 檔案:
結論
透過遵循本指南,您現在擁有一個基本但功能強大的工具,可以使用 C# 和IronXL將 DataGridView 資料匯出到 Excel 檔案。 對於需要資料分析、報告或在不同格式之間傳輸資料的應用程式來說,此功能至關重要。 請記住,嘗試使用 DataGridView 控制項和 IronXL 庫的不同功能可以實現更客製化和更高級的實作。
IronXL 提供免費試用版,您可以利用該試用版來體驗其各項功能。 授權價格從 $liteLicense 起,對於尋求在 .NET 應用程式中進行 Excel 文件操作的可靠高效解決方案的專業人士和組織來說,這是一筆值得的投資。
你的旅程並未就此結束。 繼續探索 IronXL 的更多功能以及其他增強 Windows Forms 應用程式的方法。 祝您編碼愉快!
常見問題解答
如何使用 C# 將 DataGridView 中的資料匯出到 Excel 檔案?
您可以使用 IronXL 庫在 C# 中將 DataGridView 中的資料匯出到 Excel 檔案。這包括建立一個 Windows 窗體項目,透過 NuGet 安裝 IronXL,並實現將資料從 DataGridView 傳輸到 Excel 工作表的邏輯。
將 DataGridView 匯出到 Excel 需要哪些步驟?
這些步驟包括在 Windows 窗體專案中建立 DataGridView,將其綁定到資料來源,向表單新增按鈕,並使用 IronXL 庫在按鈕的點擊事件處理程序中編寫匯出邏輯。
如何在 Visual Studio 專案中安裝 IronXL?
要在 Visual Studio 專案中安裝 IronXL,請導航至“管理 NuGet 套件”,搜尋 IronXL,然後安裝它以處理將 DataGridView 匯出到 Excel 所需的所有依賴項。
我可以使用 IronXL 匯出大型 Excel 檔案嗎?
是的,IronXL 允許匯出大型 Excel 文件,而無需 Microsoft Excel 物件庫即可提供處理大型資料集的強大功能。
在 DataGridView 匯出教學中,按鈕的作用是什麼?
教程中的按鈕會觸發匯出過程。點擊後,它會執行邏輯,使用 IronXL 庫將資料從 DataGridView 傳輸到 Excel 檔案。
IronXL 如何處理從 DataGridView 到 Excel 的資料傳輸?
IronXL 透過遍歷 DataGridView 的行和列,並將每個儲存格的資料複製到對應的 Excel 工作表儲存格中,從而簡化資料傳輸。
在使用 IronXL 匯出過程中,如何處理錯誤?
您可以透過將匯出邏輯包裝在try-catch區塊中來擷取和處理異常,從而管理錯誤,即使出現檔案存取權限等問題,也能確保平穩運行。
從 DataGridView 匯出資料後,如何儲存 Excel 檔案?
使用 IronXL 將資料傳輸到 Excel 工作表後,您可以使用 IronXL 的SaveAs方法將檔案儲存到您的系統中。
IronXL 是否提供免費試用版供用戶測試其功能?
是的,IronXL 提供免費試用版,使用者可以體驗其在 .NET 應用程式中處理 Excel 檔案的功能。此外,也提供授權許可,方便使用者進行後續開發。






