Skip to footer content
USING IRONXL

Export Data from DataGridView to Excel in VB .NET 2010 Using IronXL

Exporting Data from DataGridView to Excel in VB.NET Windows Forms Applications

Exporting data from a DataGridView to an Excel file is a common requirement in VB.NET Windows Forms applications. Whether building reporting tools, data management systems, or business applications that pull data from a database, developers need a reliable method to transfer grid data into spreadsheets. This article demonstrates how to export DataGridView to Excel using IronXL, a modern .NET library that eliminates the need for Microsoft Office installation.

Introduction to Windows Forms

Windows Forms is a foundational graphical user interface (GUI) library in Microsoft’s .NET Framework, designed for building robust desktop applications with rich, interactive user experiences. As a core part of the .NET ecosystem, Windows Forms offers developers a comprehensive set of controls, including the versatile DataGridView control, which is widely used for displaying, editing, and managing data in a tabular format.

One of the most common requirements in Windows Forms applications is the ability to export data from the DataGridView control to external file formats, such as Excel files (xlsx) or CSV files. This functionality is essential for scenarios like reporting, data analysis, and sharing information with other systems or users. Whether you’re working with a small dataset or a large table sourced from a database, having a reliable method to export your data can greatly enhance the usability and value of your application.

There are several approaches to exporting DataGridView data in Windows Forms. Traditional methods often involve Microsoft Office automation, where developers use the Excel application object to create a new workbook, add a worksheet, and programmatically write each row and column from the DataGridView to the Excel file. This method provides granular control over the output, allowing you to customize the header row, column headers, and cell formatting. However, it requires Microsoft Office to be installed on the target machine, which can be a limitation for some deployments.

Alternatively, modern third-party libraries such as ClosedXML, Syncfusion, or IronXL (as featured in this article) offer streamlined APIs for exporting data to Excel files without the need for Microsoft Office. These libraries simplify the process, enabling developers to quickly generate XLSX files with custom formatting, styled header rows, and properly typed columns. They also tend to offer better performance and easier deployment, especially in server or cloud environments where Office may not be available.

How Can Developers Set Up the Project and Install the Library?

Before writing any export code, set up a VB.NET Windows Forms project in Visual Studio. This tutorial targets .NET 8, though IronXL supports .NET Framework 4.6.2 and all modern .NET versions. Note that this approach works for applications originally created in VB.NET 2010 or later.

Prerequisites:

  • Visual Studio 2022 or later
  • .NET 8 SDK installed
  • A Windows Forms App project with a DataGridView control

Install IronXL via NuGet Package Manager:

Open the Package Manager Console in Visual Studio and run:

Install-Package IronXL.Excel

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

Alternatively, right-click the project in Solution Explorer, select "Manage NuGet Packages," search for IronXL.Excel, and click Install. This library replaces the need for Microsoft Office Interop references.

Once installed, import the IronXL namespace at the top of any VB.NET file where Excel functionality is needed:

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

How Can Developers Populate a DataGridView with Sample Data?

For this example, create a simple Windows Form with a DataGridView control and a Button. The DataGridView displays employee records stored in a DataTable object that will be exported to an Excel file.

Add the following code to the form's Load event to populate the grid with sample data from a table structure:

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

This code creates a DataTable with four columns representing typical employee information. Each column is defined with its data type using GetType() for Integer, String, and Decimal values. The DataSource property binds this data directly to the DataGridView control, automatically populating the grid when the user opens the form. In production applications, this data might be loaded from a database or array instead.

Output

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

How Can Developers Export DataGridView Data to an Excel File with Headers?

The export function belongs in the Button's click event handler. The following code iterates through the DataGridView's columns and rows using a loop, writing each cell value to the corresponding Excel worksheet cells.

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

The code begins by creating a new WorkBook object, which represents the entire Excel file. The DefaultWorkSheet property provides access to the default sheet where data will be written.

Output

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

The first loop extracts column headers from the DataGridView and places them in the header row (index zero) of the Excel sheet. The HeaderText property contains the display name for each column. Using Dim colIndex As Integer declares the variable used as the loop counter.

The nested loops handle the actual data transfer. For each row in the DataGridView, the code iterates through all columns using the Count property. The method retrieves the cell value and uses ToString() to convert it to a String before writing it to the worksheet. The rowIndex + 1 offset ensures data starts below the headers row. A null check prevents errors when cells contain no value.

Finally, the SaveAs method writes the workbook to disk in XLSX format at the specified path. IronXL handles all the complex XML packaging that the Open XML format requires. The End Sub line closes the event handler function.

How Can Developers Preserve Cell Formatting in the Exported File?

Basic export transfers data, but professional applications often require formatting the output Excel file. IronXL's styling API enables formatting cells to match or enhance the DataGridView appearance.

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

This enhanced version applies professional formatting to the exported Excel file. The GetRange method selects cells using standard Excel notation (A1:D1 for the header row). The Style property exposes format options, including font weight, background color, and text color, specified as hex values.

Output

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

The salary column receives currency formatting through the Format property, which accepts Excel number format strings. When the user opens the output file in MS Excel, values in column D display with dollar signs and thousand separators. This page demonstrates just one example of the formatting capabilities available.

Why Choose a Modern Library Over Office Interop?

Traditional VB.NET solutions for Excel export relying on Microsoft.Office.Interop.Excel require Microsoft Office to be installed on every system running the application. Code using Dim xlApp patterns creates deployment challenges, especially for server environments and cloud applications, where you cannot install MS Excel.

IronXL operates independently—no Office installation needed. Applications deploy as self-contained units without external dependencies. Additionally, IronXL avoids the memory leaks and COM object cleanup issues that plague Interop-based solutions, resulting in more stable applications. The library also supports CSV export if you need that format instead of XLSX.

I hope this article has answered your question on how to export DataGridView data. For additional help, link to the troubleshooting documentation or contact support if you encounter any errors during implementation.

Conclusion

Exporting DataGridView data to Excel in VB.NET becomes straightforward with the right tools. IronXL provides a clean, modern API that handles workbook creation, data writing to cells, and formatting without requiring Microsoft Office installation. Whether you need to write simple data tables or complex formatted workbooks, this library offers the functionality you need.

Download IronXL to start building Excel export functionality into VB.NET Windows Forms applications today. Licensing options are available for teams of all sizes, with a free trial to get started.

Frequently Asked Questions

What is the easiest way to export DataGridView data to Excel in VB.NET?

Using IronXL, you can easily export DataGridView data to Excel in VB.NET with minimal code. IronXL simplifies the process by allowing direct manipulation of Excel files without needing Excel installed on the server.

How can I use IronXL to handle Excel files in a VB.NET application?

IronXL provides a straightforward API for handling Excel files, enabling VB.NET applications to read, edit, and export Excel documents seamlessly. It supports various Excel file formats and offers robust functionalities.

Does IronXL support exporting large DataGridView datasets to Excel?

Yes, IronXL is designed to efficiently handle large datasets, making it ideal for exporting extensive DataGridView data to Excel without performance bottlenecks.

Is IronXL compatible with VB.NET 2010 for Excel operations?

IronXL is fully compatible with VB.NET 2010, allowing developers to integrate advanced Excel functionalities into their applications without upgrading their development environment.

What are the benefits of using IronXL for Excel exports in VB.NET?

IronXL offers numerous benefits, including ease of use, support for multiple Excel formats, no need for Excel to be installed on the server, and powerful data manipulation capabilities.

Can IronXL export DataGridView data to different Excel formats?

Yes, IronXL supports exporting DataGridView data to various Excel formats, including XLSX, XLS, and CSV, ensuring compatibility with different user requirements and applications.

What makes IronXL a better choice compared to other Excel libraries for VB.NET?

IronXL stands out because of its simplicity, performance efficiency, and comprehensive feature set, making it a superior choice for Excel operations in VB.NET compared to other libraries.

How do I start using IronXL in my VB.NET project?

To start using IronXL in your VB.NET project, you can install it via NuGet Package Manager and refer to the official documentation for detailed guidance on integration and usage.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More