跳過到頁腳內容
使用 IRONXL

如何在 VB.NET 中將 DataGridView 導出到 Excel

從 Windows Forms DataGridView 導出數據到 Excel 是商業應用程式中的常見需求。 無論是生成報告、創建數據備份,還是與利益相關者共享信息,開發人員都需要可靠的方法來將 GridView 數據內容導出到 Excel 格式。 儘管使用 Microsoft Office Interop 的傳統方法可以達到此目的,但它們伴隨著部署的複雜性和依賴要求,這可能會使應用程式的分發變得複雜。

本教程展示了一個實際的 VB.NET 示例,使用 IronXL 將 DataGridView 數據導出到 Excel,這是一個強大的 .NET 庫,無需安裝 Microsoft Office。 我們將探討如何實現一個清晰、高效的導出解決方案,該解決方案可在不同環境中運行,包括雲平台和容器,使其成為現代 .NET Excel 操作場景的理想選擇。

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 1 - IronXL

為什麼將 DataGridView 導出到 Excel 是必不可少的?

DataGridView 控件是 Windows Forms 應用程式的基礎,顯示用戶每天交互的表格式數據。 將這些數據導出到 Excel 可使用戶利用 Excel 的強大分析工具,創建演示文稿,並與可能無法訪問應用程式的同事共享數據。 此 VB.NET Excel 導出功能對商業報告至關重要。

使用 Microsoft.Office.Interop.Excel 的傳統導出方法要求在每台運行應用程式的計算機上安裝 Excel。 這會帶來部署挑戰,尤其是在服務器環境中或在將應用程式分發給沒有 Office 授權的用戶時。 此外,如果處理不當,Interop 方法可能會遭受內存洩漏和 COM 對象清理問題。

現代 .NET 應用程式需要更加靈活的解決方案。 IronXL 通過提供一個獨立的庫來應對這些挑戰,該庫生成的 Excel 文件不依賴於任何 Microsoft Office。 這種方法確保了在開發、測試和生產環境中的一致功能,同時支持在 Office 安裝不可行的情況下部署到容器和雲平台。在生產環境中使用內置所有功能需要有效的授權金鑰。

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 2 - 跨平台

如何使用 IronXL 將 GridView 導出到 Excel VB .NET 示例?

讓我們從在 VB.NET 專案中設置 IronXL 開始。 在 Visual Studio 中打開 Package Manager Console,然後使用以下命令安裝 IronXL:

Install-Package IronXL.Excel

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 3 - 安裝

有關詳細的安裝選項,請參閱 IronXL 安裝指南。 安裝後,將 Imports IronXL 添加到您的 VB .NET 專案文件中,以訪問庫的 Excel 導出功能。

首先,我們將創建一個包含導入數據的 DataGridView 的範例 Windows Forms 應用程式。 以下是設置表單和實現導出功能的完整代碼:

Imports IronXL
Imports System.Windows.Forms
Imports System.Data
Public Class Form1
    ' Type GridView
    Private dataGridView1 As DataGridView
    Private btnExport As Button
    Public Sub New()
        InitializeComponent()
        SetupControls()
        LoadSampleData()
    End Sub
    Private Sub SetupControls()
        ' Initialize DataGridView
        dataGridView1 = New DataGridView()
        dataGridView1.Location = New Point(10, 10)
        dataGridView1.Size = New Size(450, 200)
        ' Initialize Export Button
        btnExport = New Button()
        btnExport.Text = "Export to Excel"
        btnExport.Location = New Point(10, 220)
        btnExport.Size = New Size(120, 30)
        AddHandler btnExport.Click, AddressOf ExportToExcel
        ' Add controls to form
        Me.Controls.Add(dataGridView1)
        Me.Controls.Add(btnExport)
        Me.Text = "DataGridView to Excel Export"
        Me.Size = New Size(500, 300)
    End Sub
    Private Sub LoadSampleData()
        ' Create sample DataTable
        Dim dt As New DataTable()
        dt.Columns.Add("Product ID", GetType(Integer))
        dt.Columns.Add("Product Name", GetType(String))
        dt.Columns.Add("Category", GetType(String))
        dt.Columns.Add("Price", GetType(Decimal))
        dt.Columns.Add("Stock", GetType(Integer))
        ' Add sample rows
        dt.Rows.Add(1001, "Laptop Pro", "Electronics", 1299.99, 15)
        dt.Rows.Add(1002, "Wireless Mouse", "Accessories", 29.99, 50)
        dt.Rows.Add(1003, "USB-C Cable", "Accessories", 19.99, 100)
        dt.Rows.Add(1004, "Monitor 27""", "Electronics", 399.99, 8)
        dt.Rows.Add(1005, "Keyboard Mechanical", "Accessories", 89.99, 25)
        ' Bind to DataGridView
        dataGridView1.DataSource = dt
    End Sub
    Private Sub ExportToExcel(ByVal sender As Object, ByVal e As EventArgs)
        Try
            ' Create new Excel workbook
            Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
            Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
            ' Export column headers
            For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
                worksheet.SetCellValue(0, colIndex, dataGridView1.Columns(colIndex).HeaderText)
            Next
            ' Export data rows
            For rowIndex As Integer = 0 To dataGridView1.Rows.Count - 1
                If Not dataGridView1.Rows(rowIndex).IsNewRow Then
                    For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
                        Dim cellValue = dataGridView1.Rows(rowIndex).Cells(colIndex).Value
                        If TypeOf cellValue Is Decimal OrElse TypeOf cellValue Is Double OrElse TypeOf cellValue Is Integer Then
    worksheet.SetCellValue(rowIndex + 1, colIndex, cellValue)
Else
    worksheet.SetCellValue(rowIndex + 1, colIndex, cellValue.ToString())
End If
                    Next
                End If
            Next
            ' Save the Excel file
            Dim saveDialog As New SaveFileDialog()
            saveDialog.Filter = "Excel Files|*.xlsx"
            saveDialog.Title = "Save Excel File"
            saveDialog.FileName = "DataGridViewExport.xlsx"
            If saveDialog.ShowDialog() = DialogResult.OK Then
                workbook.SaveAs(saveDialog.FileName)
                MessageBox.Show("Export completed successfully!", "Success", 
                              MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Export failed: " & ex.Message, "Error", 
                          MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class
Imports IronXL
Imports System.Windows.Forms
Imports System.Data
Public Class Form1
    ' Type GridView
    Private dataGridView1 As DataGridView
    Private btnExport As Button
    Public Sub New()
        InitializeComponent()
        SetupControls()
        LoadSampleData()
    End Sub
    Private Sub SetupControls()
        ' Initialize DataGridView
        dataGridView1 = New DataGridView()
        dataGridView1.Location = New Point(10, 10)
        dataGridView1.Size = New Size(450, 200)
        ' Initialize Export Button
        btnExport = New Button()
        btnExport.Text = "Export to Excel"
        btnExport.Location = New Point(10, 220)
        btnExport.Size = New Size(120, 30)
        AddHandler btnExport.Click, AddressOf ExportToExcel
        ' Add controls to form
        Me.Controls.Add(dataGridView1)
        Me.Controls.Add(btnExport)
        Me.Text = "DataGridView to Excel Export"
        Me.Size = New Size(500, 300)
    End Sub
    Private Sub LoadSampleData()
        ' Create sample DataTable
        Dim dt As New DataTable()
        dt.Columns.Add("Product ID", GetType(Integer))
        dt.Columns.Add("Product Name", GetType(String))
        dt.Columns.Add("Category", GetType(String))
        dt.Columns.Add("Price", GetType(Decimal))
        dt.Columns.Add("Stock", GetType(Integer))
        ' Add sample rows
        dt.Rows.Add(1001, "Laptop Pro", "Electronics", 1299.99, 15)
        dt.Rows.Add(1002, "Wireless Mouse", "Accessories", 29.99, 50)
        dt.Rows.Add(1003, "USB-C Cable", "Accessories", 19.99, 100)
        dt.Rows.Add(1004, "Monitor 27""", "Electronics", 399.99, 8)
        dt.Rows.Add(1005, "Keyboard Mechanical", "Accessories", 89.99, 25)
        ' Bind to DataGridView
        dataGridView1.DataSource = dt
    End Sub
    Private Sub ExportToExcel(ByVal sender As Object, ByVal e As EventArgs)
        Try
            ' Create new Excel workbook
            Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
            Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
            ' Export column headers
            For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
                worksheet.SetCellValue(0, colIndex, dataGridView1.Columns(colIndex).HeaderText)
            Next
            ' Export data rows
            For rowIndex As Integer = 0 To dataGridView1.Rows.Count - 1
                If Not dataGridView1.Rows(rowIndex).IsNewRow Then
                    For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
                        Dim cellValue = dataGridView1.Rows(rowIndex).Cells(colIndex).Value
                        If TypeOf cellValue Is Decimal OrElse TypeOf cellValue Is Double OrElse TypeOf cellValue Is Integer Then
    worksheet.SetCellValue(rowIndex + 1, colIndex, cellValue)
Else
    worksheet.SetCellValue(rowIndex + 1, colIndex, cellValue.ToString())
End If
                    Next
                End If
            Next
            ' Save the Excel file
            Dim saveDialog As New SaveFileDialog()
            saveDialog.Filter = "Excel Files|*.xlsx"
            saveDialog.Title = "Save Excel File"
            saveDialog.FileName = "DataGridViewExport.xlsx"
            If saveDialog.ShowDialog() = DialogResult.OK Then
                workbook.SaveAs(saveDialog.FileName)
                MessageBox.Show("Export completed successfully!", "Success", 
                              MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Export failed: " & ex.Message, "Error", 
                          MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class
VB .NET

這段代碼演示了核心導出功能。 SetupControls 方法創建了 DataGridView 和導出按鈕,並將它們放置在表單上。 LoadSampleData 方法使用 DataTable 填充樣本產品數據網格,DataTable 作為 VB.NET 應用程式中 DataGridView 控件的常見數據源。

ExportToExcel 方法處理實際的導出過程。 它使用 XLSX 格式創建一個新的 IronXL WorkBook,然後遍歷 DataGridView 將標題和數據導出到 Excel 工作表中。 SetCellValue 方法有效地通過行和列索引將值置入 Excel 單元格中。 代碼使用 IsNewRow 屬性跳過出現在可編輯 DataGridView 底部的空行。 這種方法確保了 Excel 輸出乾淨整潔,沒有意外的空白行。

如果要在基於 Web 的 ASP.NET 應用程式中實現此功能,可以通過將文件作為可下載回覆進一步擴展。 在這種情況下,可以使用 Content-Disposition HTTP 標頭指定 Excel 文件應在瀏覽器中內聯顯示或強制作為下載附件。 頁面生命週期渲染結束後,文件將發送到客戶端。 同樣,當 ASP.NET WebForms 開發者導出控件以確保控件在頁面生命週期之外正確呈現時,可能需要重寫 public override void VerifyRenderingInServerForm 方法。

輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 4 - DataGridView 輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 5 - Excel 輸出

如果在基於 Web 的 ASP.NET 應用程式中實現此功能,可以通過將文件作為可下載回覆進一步擴展。 在這種情況下,可以使用 Content-Disposition HTTP 標頭指定 Excel 文件應在瀏覽器中內聯顯示或強制作為下載附件。 同樣,當 ASP.NET WebForms 開發者導出控件如 GridView 到 Excel 時,可能需要重寫 public override void VerifyRenderingInServerForm 方法,以確保控件在正常的頁面生命週期之外正確呈現。

如何通過格式化增強您的 Excel 導出?

專業的 Excel 導出通常需要格式化以提高可讀性。 IronXL 在導出過程中提供廣泛的樣式功能。 這是一個包含格式化的增強版:

' Object sender
Private Sub ExportToExcelWithFormatting(sender As Object, e As EventArgs)
    Try
        Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
        ' Default Excel Worksheet
        Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
        ' Set column headers with formatting
        For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
            Dim headerCell = worksheet.GetCellAt(0, colIndex)
            headerCell.Value = dataGridView1.Columns(colIndex).HeaderText
            ' Apply header formatting
            headerCell.Style.Font.Bold = True
            headerCell.Style.BackgroundColor = "#4472C4"
            headerCell.Style.Font.Color = "#FFFFFF"
            headerCell.Style.HorizontalAlignment = HorizontalAlignment.Center
        Next
        ' Export data with alternating row colors
        For rowIndex As Integer = 0 To dataGridView1.Rows.Count - 1
            If Not dataGridView1.Rows(rowIndex).IsNewRow Then
                For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
                    Dim cellValue = dataGridView1.Rows(rowIndex).Cells(colIndex).Value
                    Dim excelCell = worksheet.GetCellAt(rowIndex + 1, colIndex)
                    If cellValue IsNot Nothing Then
                        excelCell.Value = cellValue.ToString()
                    End If
                    ' Apply alternating row colors
                    If rowIndex Mod 2 = 0 Then
                        excelCell.Style.BackgroundColor = "#F2F2F2"
                    End If
                Next
            End If
        Next
        ' Auto-fit columns
        For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
            worksheet.AutoSizeColumn(colIndex)
        Next
        ' Save formatted Excel file
        Dim saveDialog As New SaveFileDialog()
        saveDialog.Filter = "Excel Files|*.xlsx"
        If saveDialog.ShowDialog() = DialogResult.OK Then
            workbook.SaveAs(saveDialog.FileName)
            MessageBox.Show("Formatted export completed!", "Success")
        End If
    Catch ex As Exception
        MessageBox.Show("Export failed: " & ex.Message, "Error")
    End Try
End Sub
' Object sender
Private Sub ExportToExcelWithFormatting(sender As Object, e As EventArgs)
    Try
        Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
        ' Default Excel Worksheet
        Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
        ' Set column headers with formatting
        For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
            Dim headerCell = worksheet.GetCellAt(0, colIndex)
            headerCell.Value = dataGridView1.Columns(colIndex).HeaderText
            ' Apply header formatting
            headerCell.Style.Font.Bold = True
            headerCell.Style.BackgroundColor = "#4472C4"
            headerCell.Style.Font.Color = "#FFFFFF"
            headerCell.Style.HorizontalAlignment = HorizontalAlignment.Center
        Next
        ' Export data with alternating row colors
        For rowIndex As Integer = 0 To dataGridView1.Rows.Count - 1
            If Not dataGridView1.Rows(rowIndex).IsNewRow Then
                For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
                    Dim cellValue = dataGridView1.Rows(rowIndex).Cells(colIndex).Value
                    Dim excelCell = worksheet.GetCellAt(rowIndex + 1, colIndex)
                    If cellValue IsNot Nothing Then
                        excelCell.Value = cellValue.ToString()
                    End If
                    ' Apply alternating row colors
                    If rowIndex Mod 2 = 0 Then
                        excelCell.Style.BackgroundColor = "#F2F2F2"
                    End If
                Next
            End If
        Next
        ' Auto-fit columns
        For colIndex As Integer = 0 To dataGridView1.Columns.Count - 1
            worksheet.AutoSizeColumn(colIndex)
        Next
        ' Save formatted Excel file
        Dim saveDialog As New SaveFileDialog()
        saveDialog.Filter = "Excel Files|*.xlsx"
        If saveDialog.ShowDialog() = DialogResult.OK Then
            workbook.SaveAs(saveDialog.FileName)
            MessageBox.Show("Formatted export completed!", "Success")
        End If
    Catch ex As Exception
        MessageBox.Show("Export failed: " & ex.Message, "Error")
    End Try
End Sub
VB .NET

此增強版對導出的 Excel 文件應用了專業的格式化。標題使用加粗文字,藍色背景和白色字體顏色,創建了清晰的視覺區別。 代碼通過簡單的取模運算來實現交替行顏色,改善大數據集的可讀性。

AutoSizeColumn 方法調整列寬以適應內容,消除導出後手動調整的需要。 這些格式選項將基本的數據導出轉變為即時共享的準備就緒文件。

IronXL 提供了哪些額外的導出選項?

IronXL 不僅提供基本的 Excel 導出,還提供增強功能的靈活多樣的功能。 以下是可以結合的一些強大功能:

' Add formulas to calculate totals
worksheet.SetCellValue(dataGridView1.Rows.Count + 2, 3, "=SUM(D2:D" & (dataGridView1.Rows.Count + 1) & ")")
' Create multiple worksheets for categorized data
Dim summarySheet As WorkSheet = workbook.CreateWorkSheet("Summary")
summarySheet.SetCellValue(0, 0, "Total Products")
summarySheet.SetCellValue(0, 1, dataGridView1.Rows.Count - 1)
' Export to different formats
workbook.SaveAsCsv("export.csv")     ' CSV format
workbook.SaveAsJson("export.json")   ' JSON format
workbook.SaveAsXml("export.xml")     ' XML format
' Add formulas to calculate totals
worksheet.SetCellValue(dataGridView1.Rows.Count + 2, 3, "=SUM(D2:D" & (dataGridView1.Rows.Count + 1) & ")")
' Create multiple worksheets for categorized data
Dim summarySheet As WorkSheet = workbook.CreateWorkSheet("Summary")
summarySheet.SetCellValue(0, 0, "Total Products")
summarySheet.SetCellValue(0, 1, dataGridView1.Rows.Count - 1)
' Export to different formats
workbook.SaveAsCsv("export.csv")     ' CSV format
workbook.SaveAsJson("export.json")   ' JSON format
workbook.SaveAsXml("export.xml")     ' XML format
VB .NET

IronXL 支持 Excel 公式,允許您將計算直接添加到導出的文件中。範例展示了添加一個 SUM 公式來計算列總和。 創建多個工作表有助於組織複雜的導出,如將詳細數據與摘要信息分開。

庫的格式靈活性尤其有用。 儘管 XLSX 是 Excel 文件的標準,CSV 導出提供與數據庫系統和舊應用程式的通用兼容性。 JSON 和 XML 格式促進了與 Web 服務和 API 的數據交換,使 IronXL 能夠適應多樣化的集成場景。 在文件中了解有關在格式間轉換的更多信息。

輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 6 - 公式輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 7 - 多個工作表輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 8 - CSV 輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 9 - JSON 輸出

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 10 - XML 輸出

IronXL 如何簡化您的開發過程?

IronXL 最大的優勢是消除了對 Microsoft Office 的依賴。 您的應用程式無論是部署在開發人員的工作站、客戶機,還是 Docker 容器上均能一致運行。 這種獨立性簡化了部署並減少了與 Office 版本和安裝相關的支持問題。

庫的 API 設計優先考慮簡單性。 與用戶必須進行嚴格的對象處置的基於 COM 的 Interop 方法不同,IronXL 使用 VB.NET 開發者覺得自然的標準 .NET 模式。 跨平台支持意味著您的 Windows Forms 應用程式的導出功能可以在 Linux 服務器上運行的 ASP.NET Core 應用程式中重用。 欲獲得全面的文件和示例,請訪問 IronXL API 參考

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 11 - 功能

結論

使用 IronXL 將 DataGridView 數據導出到 Excel 變得容易。 該庫消除了傳統 Interop 的複雜性,同時提供專業的格式化功能和多個導出格式。 準備好提升您的 VB.NET Excel 導出功能了嗎? 從 免費試用開始,根據您的部署需求選擇合適的方案。

如何在 VB.NET 中將 DataGridView 導出到 Excel:圖 12 - 授權

常見問題解答

使用IronXL將DataGridView匯出到Excel的好處是什麼?

IronXL通過消除Microsoft Office Interop的需求來簡化將DataGridView內容匯出到Excel的過程,減少了部署的複雜性並去除依賴要求。

IronXL如何改進應用程式分發?

IronXL通過不需要Microsoft Office Interop來減少應用程式分發的複雜性,因為Office Interop通常會附帶額外的依賴性,這會使部署變得複雜。

IronXL可以在VB.NET中匯出DataGridView數據嗎?

是的,IronXL提供了一個實用的解決方案,用於在VB.NET中將DataGridView數據匯出到Excel,使其更容易在商業應用中管理數據。

將DataGridView匯出到Excel的常見用例是什麼?

常見的用例包括生成報告,創建數據備份,並在商業環境中與利益相關者分享信息。

IronXL需要系統上安裝Microsoft Excel嗎?

不,IronXL不需要安裝Microsoft Excel,因為它獨立於Excel運行,簡化了部署過程。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。