troubleshooting Question

VB.NET - Error on Export to Excel

Avatar of Wilder1626
Wilder1626Flag for Canada asked on
Visual Basic.NET
1 Comment1 Solution8 ViewsLast Modified:
Hi again.

I'm trying to export to Excel all columns from my DataGridView1.

I'm using below code:
Imports System.Data
Imports System.Reflection
Imports ClosedXML.Excel

Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles btnExportToExcel.Click
        'Creating DataTable
        Dim dt As New DataTable()

        'Adding the Columns
        For Each column As DataGridViewColumn In DataGridView1.Columns
            dt.Columns.Add(column.HeaderText, column.ValueType)

        'Adding the Rows
        For Each row As DataGridViewRow In DataGridView1.Rows
            For Each cell As DataGridViewCell In row.Cells
                dt.Rows(dt.Rows.Count - 1)(cell.ColumnIndex) = cell.Value.ToString()

        'Exporting to Excel
        Dim folderPath As String = "C:\"
        If Not Directory.Exists(folderPath) Then
        End If
        Using wb As New XLWorkbook()
            wb.Worksheets.Add(dt, "Customers")
            wb.SaveAs(folderPath & Convert.ToString("DataGridViewExport.xlsx"))
        End Using
    End Sub
The problem i have is that i'm getting below error, and i don't understand why:

What can i do to fix this problem?

Thank you.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 1 Comment.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros