使用 IRONXL 如何在 C# 中將 Datagridview 導出到 Excel Jordi Bardia 更新日期:6月 20, 2025 Download IronXL NuGet 下載 DLL 下載 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article This tutorial provides a comprehensive guide on how to export data from a DataGridView control in a Windows Forms Application to an Excel file using the IronXL library in C#. 我們將重點放在為初學者創造一個無縫的體驗,讓他們能夠將Microsoft Excel功能集成到他們的C#項目中。 如何在C#中將DataGridView導出到Excel 在Visual Studio中創建一個C# Windows Forms項目。 使用NuGet包管理器安裝Excel庫。 在Windows Form用戶介面中創建一個DataGridView和一個按鈕。 將數據源附加到DataGridView。 在按鈕的點擊事件處理器中應用數據導出邏輯。 IronXL 的入門步驟 IronXL是一個強大的庫,可以簡化在.NET Framework應用中處理Excel文檔的過程。 它允許您導出大型Excel文件,處理復雜的數據源,並在無需Microsoft Excel對象庫的情況下提供廣泛的.NET Excel文件操作支持。 讓我們設置我們的項目。 設置您的項目 1. 創建一個新的Windows Forms應用程序 打開Visual Studio並創建一個新的Windows Forms應用程序。 這將是我們的項目的基礎,我們將在此實現將DataGridView數據導出到Excel文件的功能。 2. 安裝IronXL IronXL可以輕鬆添加到您的項目中。 在Visual Studio中,導航到'管理NuGet包'選項,搜索IronXL,然後安裝它。 此操作將處理所有將DataGridView導出到C#中的Excel所需的依賴項。 3. 準備用戶介面 將DataGridView控件添加到您的表單。 此控件將保存我們想要導出的數據。 另外,添加一個按鈕來觸發導出過程。 您可以將其標記為'導出到Excel'或類似的名稱。 實現導出功能 在本節中,我們將教授如何編程功能,允許您使用IronXL將Windows Forms應用中的DataGridView數據導出到Excel文檔中的具體細節。 構建應用程序 首先,您需要將DataGridView控件添加到您的表單中。 此控件是主要組件,您的數據將在導出前顯示於此。 您可以輕鬆地從Visual Studio的工具箱中將DataGridView拖放到您的表單中。 我們還可以添加一個按鈕以將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; } 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工作表中的相應單元格。 這是通過使用索引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 輸出 一旦我們運行程序,此介面將顯示出來: 在這裡,您可以看到數據在DataGridView中顯示出來。 現在,點擊導出按鈕。 這將把DataGridView的數據導出到Excel文件中。 在此處,您可以看到彈出了消息框,並且數據已導出到Excel文件中。以下是導出的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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。 相關文章 發表日期 10月 27, 2025 如何在 C# 中創建 Excel 樞紐分析表 學習使用 C# Interop 和 IronXL 創建 Excel 中的樞紐分析表,這是一個清晰的分步指南。 閱讀更多 發表日期 10月 27, 2025 如何在 C# 中將 DataGridView 匯出為 Excel 並保留列標題 學習如何在 C# 教程中使用 IronXL library 將 DataGridView 資料匯出為 Excel 同時保留列標題。分步教學。 閱讀更多 發表日期 10月 27, 2025 如何使用 IronXL 的 .NET Core CSV 讀取器 學習使用 IronXL 作為 .NET Core CSV 讀取器的有效方法,提供實用範例。 閱讀更多 如何在 C# 控制台應用中讀取 Excel 文件如何從 CSV 文件讀取數據並...
發表日期 10月 27, 2025 如何在 C# 中將 DataGridView 匯出為 Excel 並保留列標題 學習如何在 C# 教程中使用 IronXL library 將 DataGridView 資料匯出為 Excel 同時保留列標題。分步教學。 閱讀更多