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

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

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

How to Export DataGridView to Excel in C

  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;
}
$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
}
$vbLabelText   $csharpLabel

從 DataGridView 匯出數據

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

using IronXL;
using 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");
$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();
    }
}
$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;
}
$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);
$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);
}
$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 應用程式的方法。 祝您程式愉快!

常見問題解答

如何將 DataGridView 中的資料導出到 C# 中的 Excel 文件?

可以使用 IronXL 庫將 DataGridView 中的資料導出到 C# 中的 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 傳輸到使用 IronXL 的 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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me