Question

I want to create an application where i can export my desired gridview result into a new excel file. if the file with same name already exists then it will ask to give a new name else it will create the new file.

Was it helpful?

Solution

try this out

Private Sub ButtonExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)   Handles ButtonExport.Click
    Dim rowsTotal, colsTotal As Short
    Dim I, j, iC As Short
    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
    Dim xlApp As New Excel.Application
    Try
        Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
        Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
        xlApp.Visible = True
        rowsTotal = DataGridView1.RowCount - 1
        colsTotal = DataGridView1.Columns.Count - 1
        With excelWorksheet
            .Cells.Select()
            .Cells.Delete()
            For iC = 0 To colsTotal
                .Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
            Next
            For I = 0 To rowsTotal - 1
                For j = 0 To colsTotal
                    .Cells(I + 2, j + 1).value = DataGrid1.Rows(I).Cells(j).Value
                Next j
            Next I
            .Rows("1:1").Font.FontStyle = "Bold"
            .Rows("1:1").Font.Size = 10
            .Cells.Columns.AutoFit()
            .Cells.Select()
            .Cells.EntireColumn.AutoFit()
            .Cells(1, 1).Select()
        End With
    Catch ex As Exception
        MsgBox("Export Excel Error " & ex.Message)
    Finally
        'RELEASE ALLOACTED RESOURCES
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
        xlApp = Nothing
    End Try
End Sub

OTHER TIPS

I would not recommend Rachel Gallens Solution - sure it works, but there are a lot of problems with it: It uses Interop - a technique which is very slow, error prone and impossible to do in server scenarios. Also, the Interop interface is easily 10 years old - when you have advanced problems, you end up dealing with a complex and not well documented maze.

I would suggest using EPPLUS: it is afree library which can create xlsx files on the fly and is very fast. As you can see here: all you have to do is a single Line of code: Export DataTable to excel with EPPlus

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top