跳過到頁腳內容
使用 IRONXL

在 VB .NET 2010 中使用 IronXL 將資料從 DataGridView 匯出至 Excel

在 VB.NET Windows Forms 應用程式中將資料從 DataGridView 匯出至 Excel.

在 VB.NET Windows Forms 應用程式中,將 DataGridView 中的資料匯出至 Excel 檔案是一項常見的需求。 無論是建立報表工具、資料管理系統,或是從資料庫擷取資料的商業應用程式,開發人員都需要可靠的方法將網格資料傳輸到試算表中。 本文示範如何使用 IronXLDataGridView 匯出至 Excel,IronXL.Excel 是一個現代化的 .NET 函式庫,不需要安裝 Microsoft Office。

Windows窗體簡介

Windows Forms 是 Microsoft 的 .NET Framework 中的基礎圖形使用者介面 (GUI) 函式庫,專為建立具有豐富互動使用者體驗的強大桌面應用程式而設計。 作為 .NET 生態系統的核心部分,Windows Forms 為開發人員提供了一套完整的控制項,其中包括多用途的 DataGridView 控制項,該控制項廣泛用於以表格格式顯示、編輯和管理資料。

Windows Forms 應用程式中最常見的需求之一,就是能夠將資料從 DataGridView 控件匯出至外部檔案格式,例如 Excel 檔案 (xlsx) 或 CSV 檔案。 這些功能對於報告、資料分析,以及與其他系統或使用者分享資訊等情境來說是不可或缺的。 無論您使用的是小型資料集或是來自資料庫的大型資料表,若能有可靠的方法匯出資料,將可大幅提升應用程式的可用性與價值。

在 Windows 窗体中导出 DataGridView 数据有几种方法。 傳統的方法通常涉及 Microsoft Office 自動化,開發人員使用 Excel 應用程式物件建立新的工作簿、新增工作表,並以程式化的方式將 DataGridView 中的每一行和每一列寫入 Excel 檔案。此方法提供了對輸出的細粒度控制,允許您自訂標頭行、列標頭和單元格格式。 不過,這需要在目標機器上安裝 Microsoft Office,這對某些部署可能會造成限制。

另外,ClosedXML、Syncfusion 或 IronXL.Excel(如本文中的特色)等現代第三方函式庫提供了簡化的 API,可在不需要 Microsoft Office 的情況下將資料匯出至 Excel 檔案。這些函式庫簡化了流程,讓開發人員可以快速產生具有自訂格式、樣式化標題行和正確輸入欄位的 XLSX 檔案。 這些工具也傾向於提供更好的效能和更容易的部署,特別是在可能無法使用 Office 的伺服器或雲端環境中。

開發人員如何設定專案並安裝程式庫?

在撰寫任何匯出程式碼之前,請在 Visual Studio 中設定一個 VB.NET Windows Forms 專案。 本教學以 .NET 8 為目標,雖然 IronXL 支援 .NET Framework 4.6.2 和所有現代 .NET 版本。 請注意,此方法適用於最初以 VB.NET 2010 或更新版本建立的應用程式。

先決條件:

  • Visual Studio 2022 或更新版本
  • 已安裝 .NET 8 SDK
  • 具有 DataGridView 控件的 Windows Forms App 專案

透過 NuGet 套件管理員安裝 IronXL:

在 Visual Studio 中開啟套件管理員控制台並執行:

Install-Package IronXL.Excel

Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 1 - Installation

或者,在"解決方案總管"中右鍵按一下專案,選擇"管理 NuGet 套件",搜尋 IronXL.Excel,然後按一下安裝。 本庫可取代 Microsoft Office Interop 參考資料。

安裝完成後,在任何需要 Excel 功能的 VB.NET 檔案頂端匯入 IronXL 命名空間:

Imports IronXL
Imports System.Data
Imports IronXL
Imports System.Data
VB .NET

開發人員如何使用樣本資料填充 DataGridView?

在本範例中,請建立一個簡單的 Windows 表單,其中包含一個 DataGridView 控件和一個 Button。 DataGridView 會顯示儲存於 DataTable 物件中的員工記錄,這些記錄將會匯出至 Excel 檔案。

在表單的 Load 事件中加入下列程式碼,以表格結構中的範例資料填充網格:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As New DataTable()
    ' Define columns with appropriate data type
    dt.Columns.Add("EmployeeID", GetType(Integer))
    dt.Columns.Add("Name", GetType(String))
    dt.Columns.Add("Department", GetType(String))
    dt.Columns.Add("Salary", GetType(Decimal))
    ' Add sample rows of data
    dt.Rows.Add(101, "Sarah Johnson", "Engineering", 85000)
    dt.Rows.Add(102, "Michael Chen", "Marketing", 72000)
    dt.Rows.Add(103, "Emily Davis", "Finance", 91000)
    dt.Rows.Add(104, "James Wilson", "Engineering", 78000)
    ' Set DataGridView data source
    DataGridView1.DataSource = dt
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As New DataTable()
    ' Define columns with appropriate data type
    dt.Columns.Add("EmployeeID", GetType(Integer))
    dt.Columns.Add("Name", GetType(String))
    dt.Columns.Add("Department", GetType(String))
    dt.Columns.Add("Salary", GetType(Decimal))
    ' Add sample rows of data
    dt.Rows.Add(101, "Sarah Johnson", "Engineering", 85000)
    dt.Rows.Add(102, "Michael Chen", "Marketing", 72000)
    dt.Rows.Add(103, "Emily Davis", "Finance", 91000)
    dt.Rows.Add(104, "James Wilson", "Engineering", 78000)
    ' Set DataGridView data source
    DataGridView1.DataSource = dt
End Sub
VB .NET

此代碼會建立一個 DataTable 並包含四個代表典型員工資訊的欄位。 對於 Integer, String, 和 Decimal 值,使用 GetType() 定義每一列的資料類型。 DataSource 屬性會將這些資料直接綁定到 DataGridView 控件,當使用者開啟表格時會自動填充網格。 在生產應用程式中,這些資料可能會從資料庫或陣列載入。

輸出

Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 2 - DataGridView Output

開發人員如何將 DataGridView 資料匯出到帶標頭的 Excel 檔案?

匯出功能屬於 Button 的按一下事件處理程式。 以下程式碼使用循環遍歷 DataGridView 的列和行,將每個儲存格的值寫入對應的 Excel 工作表儲存格中。

Private Sub btnExport_Click(sender As Object, e As EventArgs)
    ' Create a new Excel workbook object and worksheet
    Dim workbook As WorkBook = WorkBook.Create()
    Dim sheet As WorkSheet = workbook.DefaultWorkSheet
    ' Write column headers to the header row (row index 0), integer dim
    Dim colIndex As Integer
    For colIndex = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, colIndex, DataGridView1.Columns(colIndex).HeaderText)
    Next
    ' Write data rows starting from the second row
    Dim rowIndex As Integer
    For rowIndex = 0 To DataGridView1.Rows.Count - 1
        For colIndex = 0 To DataGridView1.Columns.Count - 1
            Dim cellValue = DataGridView1.Rows(rowIndex).Cells(colIndex).Value
            If cellValue IsNot Nothing Then
                sheet.SetCellValue(rowIndex + 1, colIndex, cellValue.ToString())
            End If
        Next
    Next
    ' Save the workbook as an XLSX file with specified filename
    Dim outputPath As String = "EmployeeData.xlsx"
    workbook.SaveAs(outputPath)
    MessageBox.Show("Export solved! File created successfully.", "Success")
End Sub
Private Sub btnExport_Click(sender As Object, e As EventArgs)
    ' Create a new Excel workbook object and worksheet
    Dim workbook As WorkBook = WorkBook.Create()
    Dim sheet As WorkSheet = workbook.DefaultWorkSheet
    ' Write column headers to the header row (row index 0), integer dim
    Dim colIndex As Integer
    For colIndex = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, colIndex, DataGridView1.Columns(colIndex).HeaderText)
    Next
    ' Write data rows starting from the second row
    Dim rowIndex As Integer
    For rowIndex = 0 To DataGridView1.Rows.Count - 1
        For colIndex = 0 To DataGridView1.Columns.Count - 1
            Dim cellValue = DataGridView1.Rows(rowIndex).Cells(colIndex).Value
            If cellValue IsNot Nothing Then
                sheet.SetCellValue(rowIndex + 1, colIndex, cellValue.ToString())
            End If
        Next
    Next
    ' Save the workbook as an XLSX file with specified filename
    Dim outputPath As String = "EmployeeData.xlsx"
    workbook.SaveAs(outputPath)
    MessageBox.Show("Export solved! File created successfully.", "Success")
End Sub
VB .NET

程式碼一開始會建立一個新的 WorkBook 物件,代表整個 Excel 檔案。DefaultWorkSheet 屬性提供對預設工作表的存取,資料將寫入其中。

輸出

Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 3 - Excel Output

第一個迴圈從 DataGridView 擷取列標題,並將其放置在 Excel 工作表的標題行(索引為零)。 HeaderText 屬性包含每列的顯示名稱。 使用 Dim colIndex As Integer 宣告用來作為循環計數器的變數。

嵌套迴圈會處理實際的資料傳輸。 對於 DataGridView 中的每一行,程式碼會使用 Count 屬性遍歷所有欄位。 該方法擷取儲存格值,並使用 ToString() 將其轉換為 String 之後,再寫入工作表。 rowIndex + 1 偏移量可確保資料從標頭行下方開始。 空值檢查可防止單元格不含任何值時發生錯誤。

最後,SaveAs 方法會將工作簿以 XLSX 格式寫入指定路徑的磁碟。 IronXL 會處理 Open XML 格式所要求的所有複雜 XML 包裝。 End Sub 行關閉事件處理函式。

開發人員如何在匯出的檔案中保留儲存格格式?

基本的匯出功能可以傳輸資料,但專業的應用程式通常需要對輸出的 Excel 檔案進行格式化。IronXL 的樣式 API 能夠格式化儲存格,以符合或強化 DataGridView 的外觀。

Private Sub ExportWithFormatting()
    Dim workbook As WorkBook = WorkBook.Create()
    Dim sheet As WorkSheet = workbook.DefaultWorkSheet
    ' Write and style column headers on the first line
    Dim colIndex As Integer
    For colIndex = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, colIndex, DataGridView1.Columns(colIndex).HeaderText)
    Next
    ' Find Salary column index (case-insensitive)
    Dim salaryColIndex As Integer = -1
    For i As Integer = 0 To DataGridView1.Columns.Count - 1
        If String.Equals(DataGridView1.Columns(i).HeaderText, "Salary", StringComparison.OrdinalIgnoreCase) Then
            salaryColIndex = i
            Exit For
        End If
    Next
    ' Apply header row styling with format options
    Dim headerRange = sheet.GetRange("A1:D1")
    headerRange.Style.Font.Bold = True
    headerRange.Style.SetBackgroundColor("#4472C4")
    headerRange.Style.Font.SetColor("#FFFFFF")
    ' Write data rows and ensure Salary cells are numeric
    For rowIndex As Integer = 0 To DataGridView1.Rows.Count - 1
        If Not DataGridView1.Rows(rowIndex).IsNewRow Then
            For colIndex = 0 To DataGridView1.Columns.Count - 1
                Dim cellValue = DataGridView1.Rows(rowIndex).Cells(colIndex).Value
                Dim targetRow = rowIndex + 1
                If cellValue Is Nothing Then
                    Continue For
                End If
                If colIndex = salaryColIndex Then
                    ' Ensure numeric value for salary column
                    Dim decValue As Decimal
                    If TypeOf cellValue Is Decimal OrElse TypeOf cellValue Is Double OrElse TypeOf cellValue Is Integer OrElse TypeOf cellValue Is Single Then
                        decValue = Convert.ToDecimal(cellValue)
                        sheet.SetCellValue(targetRow, colIndex, decValue)
                    Else
                        ' Try parse using current culture, then invariant
                        If Decimal.TryParse(cellValue.ToString(), Globalization.NumberStyles.Number, Globalization.CultureInfo.CurrentCulture, decValue) _
                       OrElse Decimal.TryParse(cellValue.ToString(), Globalization.NumberStyles.Number, Globalization.CultureInfo.InvariantCulture, decValue) Then
                            sheet.SetCellValue(targetRow, colIndex, decValue)
                        Else
                            ' fallback to text if parsing fails
                            sheet.SetCellValue(targetRow, colIndex, cellValue.ToString())
                        End If
                    End If
                Else
                    ' Non-salary: preserve numeric types, otherwise write as text
                    If TypeOf cellValue Is Decimal OrElse Type Of cellValue Is Double Or Else Type Of cellValue Is Integer Or Else Type Of cellValue Is Single Then
                        sheet.SetCellValue(targetRow, colIndex, cellValue)
                    Else
                        sheet.SetCellValue(targetRow, colIndex, cellValue.ToString())
                    End If
                End If
            Next
        End If
    Next
    ' Format salary column as currency
    Dim salaryColumn = sheet.GetRange("D2:D5")
    salaryColumn.FormatString = "$#,##0"
    Dim filename As String = "FormattedEmployeeData.xlsx"
    workbook.SaveAs(filename)
End Sub
Private Sub ExportWithFormatting()
    Dim workbook As WorkBook = WorkBook.Create()
    Dim sheet As WorkSheet = workbook.DefaultWorkSheet
    ' Write and style column headers on the first line
    Dim colIndex As Integer
    For colIndex = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, colIndex, DataGridView1.Columns(colIndex).HeaderText)
    Next
    ' Find Salary column index (case-insensitive)
    Dim salaryColIndex As Integer = -1
    For i As Integer = 0 To DataGridView1.Columns.Count - 1
        If String.Equals(DataGridView1.Columns(i).HeaderText, "Salary", StringComparison.OrdinalIgnoreCase) Then
            salaryColIndex = i
            Exit For
        End If
    Next
    ' Apply header row styling with format options
    Dim headerRange = sheet.GetRange("A1:D1")
    headerRange.Style.Font.Bold = True
    headerRange.Style.SetBackgroundColor("#4472C4")
    headerRange.Style.Font.SetColor("#FFFFFF")
    ' Write data rows and ensure Salary cells are numeric
    For rowIndex As Integer = 0 To DataGridView1.Rows.Count - 1
        If Not DataGridView1.Rows(rowIndex).IsNewRow Then
            For colIndex = 0 To DataGridView1.Columns.Count - 1
                Dim cellValue = DataGridView1.Rows(rowIndex).Cells(colIndex).Value
                Dim targetRow = rowIndex + 1
                If cellValue Is Nothing Then
                    Continue For
                End If
                If colIndex = salaryColIndex Then
                    ' Ensure numeric value for salary column
                    Dim decValue As Decimal
                    If TypeOf cellValue Is Decimal OrElse TypeOf cellValue Is Double OrElse TypeOf cellValue Is Integer OrElse TypeOf cellValue Is Single Then
                        decValue = Convert.ToDecimal(cellValue)
                        sheet.SetCellValue(targetRow, colIndex, decValue)
                    Else
                        ' Try parse using current culture, then invariant
                        If Decimal.TryParse(cellValue.ToString(), Globalization.NumberStyles.Number, Globalization.CultureInfo.CurrentCulture, decValue) _
                       OrElse Decimal.TryParse(cellValue.ToString(), Globalization.NumberStyles.Number, Globalization.CultureInfo.InvariantCulture, decValue) Then
                            sheet.SetCellValue(targetRow, colIndex, decValue)
                        Else
                            ' fallback to text if parsing fails
                            sheet.SetCellValue(targetRow, colIndex, cellValue.ToString())
                        End If
                    End If
                Else
                    ' Non-salary: preserve numeric types, otherwise write as text
                    If TypeOf cellValue Is Decimal OrElse Type Of cellValue Is Double Or Else Type Of cellValue Is Integer Or Else Type Of cellValue Is Single Then
                        sheet.SetCellValue(targetRow, colIndex, cellValue)
                    Else
                        sheet.SetCellValue(targetRow, colIndex, cellValue.ToString())
                    End If
                End If
            Next
        End If
    Next
    ' Format salary column as currency
    Dim salaryColumn = sheet.GetRange("D2:D5")
    salaryColumn.FormatString = "$#,##0"
    Dim filename As String = "FormattedEmployeeData.xlsx"
    workbook.SaveAs(filename)
End Sub
VB .NET

此增強版對匯出的 Excel 檔案套用專業格式。GetRange 方法使用標準 Excel 符號選擇儲存格 (A1:D1 為標頭行)。 Style 屬性揭露格式選項,包括指定為十六進位值的字體重量、背景顏色和文字顏色。

輸出

Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 4 - Formatted Excel Output.

薪資欄位透過 Format 屬性接收貨幣格式,該屬性接受 Excel 數字格式字串。 當使用者在 MS Excel 中開啟輸出檔案時,D 欄中的值會以美元符號和千位分隔符顯示。 本頁面僅展示了可用格式化功能的一個範例。

為何要選擇現代程式庫而非 Office Interop?

依賴 Microsoft.Office.Interop.Excel 的 Excel 匯出傳統 VB.NET 解決方案,需要在每個執行應用程式的系統上安裝 Microsoft Office。 使用 Dim xlApp 模式的程式碼會造成部署上的挑戰,尤其是對於無法安裝 MS Excel 的伺服器環境和雲端應用程式。

IronXL 可獨立運作,無需安裝 Office。 應用程式部署為獨立的單元,沒有外部依賴性。 此外,IronXL 避免了困擾基於 Interop 解決方案的記憶體洩漏和 COM 物件清理問題,使應用程式更加穩定。 如果您需要 CSV 匯出格式,而非 XLSX 格式,本資料庫也支援 CSV 匯出。

希望這篇文章能解答您關於如何匯出 DataGridView 資料的問題。 如需其他協助,請連結至 疑難排解文件,或在執行過程中遇到任何錯誤時,請聯絡支援人員。

結論

有了正確的工具,在 VB.NET 中將 DataGridView 資料匯出至 Excel 就變得簡單直接。 IronXL 提供簡潔、現代化的 API,可處理工作簿的建立、資料寫入單元格以及格式化,而無需安裝 Microsoft Office。 無論您是需要撰寫簡單的資料表或是複雜格式化的工作簿,這個函式庫都能提供您所需的功能。

下載 IronXL,立即開始在 VB.NET Windows Forms 應用程式中建立 Excel 匯出功能。 授權選項適用於各種規模的團隊,免費試用即可開始使用。

常見問題解答

在 VB.NET 中將 DataGridView 資料匯出至 Excel 的最簡單方法是什麼?

使用 IronXL,您可以在 VB.NET 中以最少的程式碼輕鬆地將 DataGridView 資料匯出至 Excel。IronXL 可直接操作 Excel 檔案,無需在伺服器上安裝 Excel,簡化了操作過程。

如何在 VB.NET 應用程式中使用 IronXL 處理 Excel 檔案?

IronXL for .NET 提供了直接的 API 來處理 Excel 檔案,讓 VB.NET 應用程式能夠無縫讀取、編輯和匯出 Excel 文件。它支援各種 Excel 檔案格式,並提供強大的功能。

IronXL.Excel 是否支援匯出大型 DataGridView 資料集至 Excel?

是的,IronXL 旨在高效處理大型資料集,因此非常適合將大量 DataGridView 資料匯出至 Excel,而不會出現效能瓶頸。

IronXL 是否與 Excel 操作的 VB.NET 2010 相容?

IronXL for .NET 與 VB.NET 2010 完全相容,讓開發人員無需升級開發環境,即可將 Excel 的進階功能整合至應用程式中。

在 VB.NET 中使用 IronXL 進行 Excel 匯出有哪些好處?

IronXL.Excel 具有眾多優點,包括易於使用、支援多種 Excel 格式、無需在伺服器上安裝 Excel 以及強大的資料處理功能。

IronXL 能將 DataGridView 資料匯出成不同的 Excel 格式嗎?

是的,IronXL.Excel 支援將 DataGridView 資料匯出成各種 Excel 格式,包括 XLSX、XLS 和 CSV,以確保能相容於不同的使用者需求和應用程式。

與其他適用於 VB.NET 的 Excel 函式庫相比,是什麼讓 IronXL 成為更好的選擇?

IronXL 之所以能脫穎而出,是因為它簡單易用、效能高效、功能全面,與其他函式庫相比,IronXL 是在 VB.NET 中進行 Excel 操作的上佳選擇。

如何開始在我的 VB.NET 專案中使用 IronXL?

若要開始在您的 VB.NET 專案中使用 IronXL,您可以透過 NuGet Package Manager 安裝,並參閱官方文件以取得整合與使用的詳細指引。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。