datagridview to excel - progressbar vb.net - vb.net

I have a button that let's me export a datagridview to excel. Sometimes it has more than 5000 rows, so it takes a bit longer.
I tried to add a progress bar, but it is simply random ( the way it is below).
How can i implement the progressbar in a better way ? i don't think i need the timer anyway .
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "template.xlsx")
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
'Dim rTargetCell As Excel.Range
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
'TEST!
For i = 0 To i = ProgressBar1.Maximum
ProgressBar1.Value = i
ProgressBar1.Update()
Timer2.Start()
System.Threading.Thread.Sleep(25)
Next
'End Test!
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Open(xlPath)
xlWorkSheet = xlWorkBook.Worksheets("data")
For i = 0 To DataGridView2.RowCount - 1
For j = 0 To DataGridView2.ColumnCount - 1
For k As Integer = 1 To DataGridView2.Columns.Count
xlWorkSheet.Cells(i + 1, j + 1) = DataGridView2(j, i).Value
Next
Next
Next
xlWorkSheet.SaveAs("C:\Users\User\Desktop\" & TextBox3.Text & ".xlsx")
xlWorkBook.Close()
xlApp.Quit()
Process.Start("C:\Users\User\Desktop\" & TextBox3.Text & ".xlsx")
Me.Close()
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
ProgressBar1.Increment(1)
Label3.Text = "(...)"
If ProgressBar1.Maximum = DataGridView2.Rows.Count Then
Label3.Text = "Finished"
End If
Timer2.Stop()
End Sub

Assuming your progress bar is from min value 0 to max value 100. You should divide the row you are about to dump into excel by 100.
e.g under this line For i = 0 To DataGridView2.RowCount - 1
put this line ProgressBar1.Value = Int(i * (ProgressBar1.Maximum / DataGridView2.RowCount))
Then under that put this line to make sure the view updates, as you are not running the progress bar updates on a separate thread.My.Application.DoEvents()
So it should look like this
For i = 0 To DataGridView2.RowCount - 1
ProgressBar1.Value = Int(i * (ProgressBar1.Maximum / DataGridView2.RowCount))
My.Application.DoEvents()
For j = 0 To DataGridView2.ColumnCount - 1
For k As Integer = 1 To DataGridView2.Columns.Count
xlWorkSheet.Cells(i + 1, j + 1) = DataGridView2(j, i).Value
Next
Next
Next

You could try something like the below. before you start the loop you can set the progressbar maximum value to the total number or records you have.
me.progressbar1.maximum = DataGridView2.RowCount
For i = 0 To DataGridView2.RowCount - 1
For j = 0 To DataGridView2.ColumnCount - 1
For k As Integer = 1 To DataGridView2.Columns.Count
xlWorkSheet.Cells(i + 1, j + 1) = DataGridView2(j, i).Value
Next
Next
Me.ProgressBar1.performstep() 'increment your bar with each record
Next

Related

DataGridView to Excel - numbers saved as text

I have a VB.Net form that lets me save a DataGridView as Excel, but it saves the numbers as text. That means that the pie charts and stuff don't "refresh".
Should I format the columns with numbers in the VB code or is there another way to save numbers as numbers?
Once I used an Excel template, where the DataGridView values go to an existing file. I thought that they would be formatted the way the cells were formatted.
This is part of the code I'm using.
Private Sub ButtonExport_Click(sender As Object, e As EventArgs) Handles ButtonExport.Click
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "template.xlsx")
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Open(xlPath)
xlWorkSheet = xlWorkBook.Worksheets("data")
For i = 0 To DataGridView1.RowCount - 1
For j = 0 To DataGridView1.ColumnCount - 1
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(i + 1, j + 4) = DataGridView1(j, i).Value
Next
Next
Next
xlWorkSheet.SaveAs("C:\Users\User\Desktop\" & TextBox3.Text & ".xlsx")
xlWorkBook.Close()
xlApp.Quit()
Me.Close()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
End Sub
I already tried DataGridView1.Columns(2).ValueType = GetType(Decimal) but it does nothing.
answered by the OP, again :D
For i = 0 To DataGridView2.RowCount - 1
For j = 0 To DataGridView2.ColumnCount - 1
Dim val As Object = DataGridView2(2, i).Value
If IsDBNull(val) Then
xlWorkSheet.Cells(i + 1, 3) = Nothing
Else
xlWorkSheet.Cells(i + 1, 3) = CDbl(val)
End If
Next
Next

Delete Blank Rows after exporting from Datagridview to excel

Good day Guys. This Code enables me to export datagridview to excel excluding invisible rows using button.
The problems is. this code leaves a blank rows in my excel everytime datagridview.row is invisible.
Can someone help me how to delete a blank row using excel-vba macro? after the "NEXT I" line?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xlapp As Microsoft.Office.Interop.Excel.Application
Dim misvalue As Object = System.Reflection.Missing.Value
Dim rowsTotal, colsTotal As Short
Dim I, J As Short
xlapp = New Microsoft.Office.Interop.Excel.Application
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
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()
Dim curCol As Short = 0
For iC = 0 To colsTotal
If DataGridView1.Columns(iC).Visible Then
.Cells(1, curCol + 1).Value = DataGridView1.Columns(iC).HeaderText
curCol += 1
End If
Next
For I = 0 To rowsTotal
curCol = 0
For J = 0 To colsTotal
DataGridView1.Rows(I).Visible = True
.Cells(I + 2, curCol + 1).value = DataGridView1.Rows(I).Cells(J).Value
curCol += 1
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()
excelWorksheet.SaveAs("E:\vbexcel.xlsx")
xlapp.Quit()
xlapp.Quit()
releaseObject(xlapp)
releaseObject(excelBook)
releaseObject(excelWorksheet)
End With
MsgBox("You can find the file E:\vbexcel.xlsx")
Dim res As MsgBoxResult
res = MsgBox("Process completed, Would you like to open the file?", MsgBoxStyle.YesNo)
If (res = MsgBoxResult.Yes) Then
Process.Start("E:\vbexcel.xlsx")
End If
End Sub
You are using same variables to get next cell of DataGridView and Excel Sheet, that is why it is inserting blank rows for invisible rows/columns
' variables to access grid cell
Dim gvRow as Integer = 0, gvCol as Integer = 0
' variables to access excel cell
Dim exRow as Integer = 0, exCol as Integer = 0
For gvRow = 0 To DataGridView1.RowCount - 1
exCol = 0
If DataGridView1.Rows(gvRow).Visible Then
For gvCol = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Columns(gvCol).Visible Then
.Cells(exRow, exCol).value = DataGridView1.Rows(gvRow).Cells(gvCol).Value
exCol += 1
End If
Next gvCol
exRow += 1
End If
Next gvRow

export datagridview header column to excel vb 2012

i'm using visual studio 2012 and microsoft SQL server 2012 to export datagridview to excel using this coding:
Public Class Export
Private Sub Export_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
ClassKoneksi.namadatabase = "KPIRWAN"
Dim dssiswa As New DataSet
Dim sql As String
sql = "select*from Siswa order by NIS ASC"
dssiswa = ClassSiswa.displayData(ClassSiswa.opencon, sql, "DataSiswa")
DataGridView1.DataSource = dssiswa
DataGridView1.DataMember = "DataSiswa"
DataGridView1.ReadOnly = True
ClassSiswa.closecon()
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ExportExcel()
End Sub
Private Sub ExportExcel()
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim oValue As Object = System.Reflection.Missing.Value
Dim sPath As String = String.Empty
Dim dlgSave As New SaveFileDialog
dlgSave.DefaultExt = "xls"
dlgSave.Filter = "Microsoft Excel|*.xls"
dlgSave.InitialDirectory = Application.StartupPath
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
xlApp = New Microsoft.Office.Interop.Excel.Application
xlBook = xlApp.Workbooks.Add(oValue)
xlSheet = xlBook.Worksheets("sheet1")
Dim xlRow As Long = 2
Dim xlCol As Short = 1
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(1, xlCol) = DataGridView1(k, 0).Value
xlCol += 1
Next
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(2, xlCol) = DataGridView1(k, 0).Value
xlCol += 1
Next
For i As Integer = 0 To DataGridView1.RowCount - 1
xlCol = 1
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(xlRow, xlCol) = DataGridView1(k, i).Value
xlCol += 1
Next
xlRow += 1
Next
xlSheet.Columns.AutoFit()
Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx")
xlSheet.SaveAs(sFileName)
xlBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlBook)
releaseObject(xlSheet)
MsgBox("Data successfully exported.", MsgBoxStyle.Information, "PRMS/SOB Date Tagging")
Catch
MsgBox(ErrorToString)
Finally
End Try
End If
End Sub
End Class
it work perfectly fine except when i exported the datagridview to excel the column header text in the datagridview is not exported to excel sheet only the gridview.
how do i make the coding to get the column header text to excel sheet?
I think you'll have to get the HeaderText from each column like this:
xlSheet.Cells(x,y).Value = DataGridView1.Columns(k).HeaderText
You would put this in your "k" loop. And then write it wherever you want in the file. x and y have to be the location where you write the header (maybe determined by k)
EDIT: writing the headers in first row of excel
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(1,k+1).Value = DataGridView1.Columns(k).HeaderText
Next

Use background worker and update the status

I am triying to use background worker for my data which process 1k+ records and update them to the excel sheet. So I thought of using the background worker and the background worker gets hit but coming out of it and triggering the background work completed event without performing its action.
Below is my code:
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
ProgressBar1.Maximum = 100
ProgressBar1.Step = 1
ProgressBar1.Value = 0
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If cmbAccounts.SelectedIndex = 0 Then
Dim Input1 As String = Directory.GetCurrentDirectory & "\Samples\abc.xlsx"
Dim tdate As String = Me.PresentDate.Value.ToString("yyyy-MM-dd")
Using myConnection As New SqlConnection("Data Source=mydatasource;Initial Catalog=db0XXX;Persist Security Info=True;User ID=sa;Password=abcd"), myCommand As New SqlCommand("GetLog", myConnection), adapter As New SqlDataAdapter(myCommand)
myConnection.Open()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#AccountID", 123)
myCommand.Parameters.AddWithValue("#Date", tdate)
' Create the DataAdapter
Dim myDataAdapter As New SqlDataAdapter(myCommand)
' Create the DataSet
Dim myDataSet As New DataSet
' Fill the DataSet
myDataAdapter.Fill(myDataSet)
Me.DataGridView1.DataSource = myDataSet.Tables(0)
Me.DataGridView2.DataSource = myDataSet.Tables(1)
Me.DataGridView3.DataSource = myDataSet.Tables(2)
' Close the connection
myConnection.Close()
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook = xlApp.Workbooks.Open(Input1)
xlWorkBook.Sheets(1).activate()
xlApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignCenter
xlApp.DisplayAlerts = False
xlApp.Columns.ColumnWidth = 25
For i = 1 To myDataSet.Tables(0).Rows.Count
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(i + 1, j + 1) = _
myDataSet.Tables(0).Rows(i - 1)(j).ToString()
Next
Next
EndOfFirstTable = myDataSet.Tables(0).Rows.Count + 1
Dim SecondTableFirstRow As Integer = EndOfFirstTable + 1
For i = 1 To myDataSet.Tables(1).Rows.Count
For j = 0 To myDataSet.Tables(1).Columns.Count - 1
xlApp.Cells(i + SecondTableFirstRow, j + 1) = _
myDataSet.Tables(1).Rows(i - 1)(j).ToString()
Next
Next
EndOfSecondTable = myDataSet.Tables(1).Rows.Count + 1
Dim ThirdTableFirstRow As Integer = EndOfSecondTable + 1
For i = 1 To myDataSet.Tables(2).Rows.Count
For j = 0 To myDataSet.Tables(2).Columns.Count - 1
xlApp.Cells(i + ThirdTableFirstRow, j + 1) = _
myDataSet.Tables(2).Rows(i - 1)(j).ToString()
Next
Next
EndOfThirdTable = myDataSet.Tables(2).Rows.Count + 1
If DataGridView1.Rows.Count - 1 + DataGridView2.Rows.Count - 1 + DataGridView3.Rows.Count - 1 = 0 Then
For i = 1 To 2
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(2, j + 1) = "NULL"
Next
Next
End If
xlApp.Columns.AutoFit()
Dim rSearchRange As Range
rSearchRange = xlWorkBook.Sheets(1).UsedRange.Columns(1)
'for example
If xlApp.WorksheetFunction.CountBlank(rSearchRange) Then
rSearchRange.SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete()
End If
lblChargeEntry.Text = DataGridView1.RowCount - 1 + DataGridView2.RowCount - 1 + DataGridView3.RowCount - 1
value1 = lblChargeEntry.Text
Dim _
Destinationpath As String = Directory.GetCurrentDirectory & "\Output\abc_" & tdate & ".xlsx"
xlApp.ActiveWorkbook.SaveAs(Destinationpath)
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
End Using
Using myConnection As New SqlConnection("Data Source=mydatasource;Initial Catalog=db0XXX;Persist Security Info=True;User ID=sa;Password=abcd"), myCommand As New SqlCommand("GetLog", myConnection), adapter As New SqlDataAdapter(myCommand)
Dim Input2 As String = Directory.GetCurrentDirectory & "\Samples\bbc.xls"
myConnection.Open()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#AccountID", 234)
myCommand.Parameters.AddWithValue("#Date", tdate)
' Create the DataAdapter
Dim myDataAdapter As New SqlDataAdapter(myCommand)
' Create the DataSet
Dim myDataSet As New DataSet
' Fill the DataSet
myDataAdapter.Fill(myDataSet)
Me.DataGridView4.DataSource = myDataSet.Tables(0)
' Close the connection
myConnection.Close()
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook = xlApp.Workbooks.Open(Input2)
xlWorkBook.Sheets(1).activate()
xlApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignCenter
xlApp.DisplayAlerts = False
xlApp.Columns.ColumnWidth = 25
Try
Dim EndOfFirstTable As Integer
For i = 1 To myDataSet.Tables(0).Rows.Count
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(i + 1, j + 1) = _
myDataSet.Tables(0).Rows(i - 1)(j).ToString()
Next
Next
EndOfFirstTable = myDataSet.Tables(0).Rows.Count + 1
If DataGridView4.Rows.Count - 1 = 0 Then
For i = 1 To 2
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(2, j + 1) = "NULL"
Next
Next
End If
xlApp.Columns.AutoFit()
Catch
End Try
Dim rSearchRange As Range
rSearchRange = xlWorkBook.Sheets(1).UsedRange.Columns(1)
'for example
If xlApp.WorksheetFunction.CountBlank(rSearchRange) Then
rSearchRange.SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete()
End If
lblPaymentPosting.Text = DataGridView4.RowCount - 1
value2 = lblPaymentPosting.Text
Dim _
Destinationpath As String = Directory.GetCurrentDirectory & _
"\Output\bbc_" & tdate & ".xls"
xlApp.ActiveWorkbook.SaveAs(Destinationpath)
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
cmbAccounts.SelectedIndex = 1
End Using
End If
If cmbAccounts.SelectedIndex = 1 Then
Dim Input3 As String = Directory.GetCurrentDirectory & "\Samples\123.xlsx"
Dim tdate As String = Me.PresentDate.Value.ToString("yyyy-MM-dd")
Using myConnection As New SqlConnection("Data Source=mydatasource;Initial Catalog=db0XXX;Persist Security Info=True;User ID=sa;Password=abcd"), myCommand As New SqlCommand("GetLog", myConnection), adapter As New SqlDataAdapter(myCommand)
myConnection.Open()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#AccountID", 234)
myCommand.Parameters.AddWithValue("#Date", tdate)
' Create the DataAdapter
Dim myDataAdapter As New SqlDataAdapter(myCommand)
' Create the DataSet
Dim myDataSet As New DataSet
' Fill the DataSet
myDataAdapter.Fill(myDataSet)
Me.DataGridView1.DataSource = myDataSet.Tables(0)
Me.DataGridView2.DataSource = myDataSet.Tables(1)
Me.DataGridView3.DataSource = myDataSet.Tables(2)
' Close the connection
myConnection.Close()
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook = xlApp.Workbooks.Open(Input3)
xlWorkBook.Sheets(1).activate()
xlApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignCenter
xlApp.DisplayAlerts = False
xlApp.Columns.ColumnWidth = 25
For i = 1 To myDataSet.Tables(0).Rows.Count
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(i + 1, j + 1) = _
myDataSet.Tables(0).Rows(i - 1)(j).ToString()
Next
Next
EndOfFirstTable = myDataSet.Tables(0).Rows.Count + 1
Dim SecondTableFirstRow As Integer = EndOfFirstTable + 1
For i = 1 To myDataSet.Tables(1).Rows.Count
For j = 0 To myDataSet.Tables(1).Columns.Count - 1
xlApp.Cells(i + SecondTableFirstRow, j + 1) = _
myDataSet.Tables(1).Rows(i - 1)(j).ToString()
Next
Next
EndOfSecondTable = myDataSet.Tables(1).Rows.Count + 1
Dim ThirdTableFirstRow As Integer = EndOfSecondTable + 1
For i = 1 To myDataSet.Tables(2).Rows.Count
For j = 0 To myDataSet.Tables(2).Columns.Count - 1
xlApp.Cells(i + ThirdTableFirstRow, j + 1) = _
myDataSet.Tables(2).Rows(i - 1)(j).ToString()
Next
Next
If DataGridView1.Rows.Count - 1 + DataGridView2.Rows.Count - 1 + DataGridView3.Rows.Count - 1 = 0 Then
For i = 1 To 2
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(2, j + 1) = "NULL"
Next
Next
End If
xlApp.Columns.AutoFit()
Dim rSearchRange As Range
rSearchRange = xlWorkBook.Sheets(1).UsedRange.Columns(1) 'for example
If xlApp.WorksheetFunction.CountBlank(rSearchRange) Then
rSearchRange.SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete()
End If
lblChargeEntry.Text = DataGridView1.RowCount - 1 + DataGridView2.RowCount - 1 + DataGridView3.RowCount - 1
value3 = lblChargeEntry.Text
Dim Destinationpath As String = Directory.GetCurrentDirectory & "\Output\234_Log_" & tdate & ".xlsx"
xlApp.ActiveWorkbook.SaveAs(Destinationpath )
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
End Using
For j As Integer = 0 To 99999
Caluculate(j)
backgroundWorker.ReportProgress((j * 100) \ 100000)
Next
End If
End Sub
Private Sub Caluculate(i As Integer)
Dim pow As Double = Math.Pow(i, i)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
progressBar1.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
MsgBox("Reports created succesfully!")
End Sub
Try putting a try/catch around the if statement. That won't address the problem but should let you see the exception. You're running into a cross-threading UI access issue when accessing the ComboBox from within the thread.
See here: https://stackoverflow.com/a/5074467/264607
If you really want to access UI elements see here:
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.checkaccess.aspx

Exporting datagrid values to excel

I am trying to export values in a datagrid control to excel. The problem I'm having is that after debugging, when I click the button, the application just gets stuck. I cannot close the form either. I have to click the debug button. The excel file also is not created.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = CType(xlWorkBook.Worksheets.Item("sheet1"), Microsoft.Office.Interop.Excel.Worksheet)
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
xlApp = Nothing
xlWorkBook = Nothing
xlWorkSheet = Nothing
MsgBox("You can find the file D:\vbexcel.xlsx")
End Sub
Try this ...
For k As Integer = 0 To DataGridView1.Columns.Count - 1
xlWorkSheet.Cells(1, k + 1) = DataGridView1.Columns(k).HeaderText
Next
For i = 0 To DataGridView1.RowCount - 1
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next