Use background worker and update the status - vb.net

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

Related

datagridview to excel - progressbar 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

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

Exporting Data To Multiple Excel Sheets

I'm Using following code to export my listview to Excelsheet but the problem is i have multiple listviews which i have to export in different sheets in same excel file . . . . .
Dim flnameSaveAs As String = System.IO.Path.GetFileName(Main.spath1)
'Save Files name
Dim extension As String
extension = Path.GetExtension(Main.spath1)
Dim file As String = System.IO.Path.GetFileName(Main.spath1)
Dim FinenameA As String = System.IO.Path.GetDirectoryName(Main.spath1)
Dim savnames As String
savnames = file.Substring(0, Len(file) - Len(extension))
Dim ExportSheet As String
ExportSheet = deskPath + "\Cel_ID_TimeLine.txt"
Dim lvi As ListViewItem
Dim sb As New System.Text.StringBuilder
Dim sbhd As New System.Text.StringBuilder
Dim columns As Integer = lvCidTimeLine.Columns.Count
For ixhd As Integer = 0 To lvCidTimeLine.Columns.Count - 1
sbhd.Append(lvCidTimeLine.Columns(ixhd).Text)
sbhd.Append(vbTab)
Next
sb.Append(vbCrLf)
For Each lvi In lvCidTimeLine.Items
For ix As Integer = 0 To lvi.SubItems.Count - 1
sb.Append(lvi.SubItems(ix).Text)
If ix < lvi.SubItems.Count - 1 Then
sb.Append(vbTab)
Else
sb.Append(vbCrLf)
End If
Next
Next
Dim sw As New StreamWriter(ExportSheet)
sw.Write(sbhd.ToString)
sw.Write(sb.ToString)
sw.Close()
Dim oExcel As Excel.Application
' Create the spreadsheet
oExcel = CreateObject("Excel.Application")
oExcel.Workbooks.OpenText(ExportSheet, , , , -4142, , True)
oExcel.Cells.EntireColumn.AutoFit()
oExcel.ActiveWorkbook.SaveAs(savpath + "\" + savnames + ".xls", -4143)
oExcel.Quit()
oExcel = Nothing
So do you have any idea how to add another sheet and export another listview to it ??
Try This Code Instead
Try
Dim objExcel As New Excel.Application
Dim bkWorkBook As Excel.Workbook
Dim shWorkSheet As Excel.Worksheet
Dim shWorkSheet1 As Excel.Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = CType(bkWorkBook.ActiveSheet, Excel.Worksheet)
For i = 0 To lv1.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = lv1.Columns(i).Text
Next
For i = 0 To lv1.Items.Count - 1
For j = 0 To lv1.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = lv1.Items(i).SubItems(j).Text
Next
Next
shWorkSheet1 = bkWorkBook.Worksheets.Add(, shWorkSheet, , )
For i = 0 To lv2.Columns.Count - 1
shWorkSheet1.Cells(1, i + 1) = lv2.Columns(i).Text
Next
For i = 0 To lv2.Items.Count - 1
For j = 0 To lv2.Items(i).SubItems.Count - 1
shWorkSheet1.Cells(i + 2, j + 1) = lv2.Items(i).SubItems(j).Text
Next
Next
objExcel.Visible = False
objExcel.Application.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs(savpath + "\" + savnames + "_1" + ".xls", -4143)
objExcel.Quit()
objExcel = Nothing
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Dim proc As System.Diagnostics.Process
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
You need to ADD to the sheets collection. Interop Excel Sheets

DataGrid export to excel

I have a DataGrid control that fills with a data set.
I don't show all fields of data set in DataGrid control.
I want to create an excel file from my DataGrid.
How to get solution?
(windows form , vb net 1.1)
Try this
Link
OR
Try This
Imports Excel = Microsoft.Office.Interop.Excel
Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("sheet1")
With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "NameYourSheet"
End With
For i = 0 To DataGrid1.RowCount - 1
For j = 0 To DataGrid1.ColumnCount - 1
wSheet.Cells(i + 1, j + 1).value = DataGrid1.Rows(i).Cells(j).Value.tosring
Next j
Next i
wSheet.Columns.AutoFit()
Private Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click
Dim xlApp As Excel.Application = New Excel.Application
xlApp.SheetsInNewWorkbook = 1
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Worksheets.Item(1)
xlWorkSheet.Name = "Example_Export"
For nRow = 0 To dgvDataToExport.Rows.Count - 1
For nCol = 0 To dgvDataToExport.Columns.Count - 1
xlWorkSheet.Cells(nRow + 1, nCol + 1) = dgvDataToExport.Rows(nRow).Cells(nCol).Value
Next nCol
Next nRow
xlApp.DisplayAlerts = False
xlWorkBook.SaveAs("C:\Example.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges)
xlWorkBook.Close()
xlApp.Quit()
End Sub
Try with this one:
Sub create_excel(sender As Object, e As EventArgs)
Dim strFileName As string
Dim tw As New StringWriter()
Dim hw As New HtmlTextWriter(tw)
strFileName = "some_excel_from_datagrid.xls"
Response.ContentType = "application/vnd.msexcel"
Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName)
Response.Charset = "UTF-8"
Response.ContentEncoding = Encoding.Default
DataGridID.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
End Sub
Maybe in this princip work.
String path = #"D:\users\....";
//your path
String connStr = "Provider=//your provider;Data Source=" + path + ";Extended Properties=Excel 12.0;";
//The connection to that file
OleDbConnection conn = new OleDbConnection(connStr);
//The query
string strSQL = "SELECT * FROM [?]";
//The command
OleDbCommand cmd = new OleDbCommand(/*The query*/strSQL, /*The connection*/conn);
DataTable dT = new DataTable();
conn.Open();
try
{
OleDbDataReader dR = cmd.ExecuteReader();
dT.Load(dR);
bS.DataSource = dT;
dGV.DataSource = bS;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Try
If Not dgv.RowCount = 0 Then
Dim folderBrowser As New FolderBrowserDialog
folderBrowser.Description = "Select location to save the report"
Dim filepath1 As String = ""
If (folderBrowser.ShowDialog() = DialogResult.OK) Then
filepath1 = folderBrowser.SelectedPath
Else
Exit Sub
End If
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Try
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 = xlWorkBook.Sheets("sheet1")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim titleStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle1")
titleStyle.Font.Bold = True
titleStyle.Font.Size = "18"
titleStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
xlWorkSheet.Cells(2, 2) = "Employee Payment Report"
xlWorkSheet.Cells(2, 4) = DateAndTime.Now.ToString("dd/MM/yyyy")
xlWorkSheet.Cells(2, 2).Style = "NewStyle1"
xlWorkSheet.Cells(2, 4).Style = "NewStyle1"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'======================================================================================================
Dim headerStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle")
headerStyle.Font.Bold = True
headerStyle.Font.Size = "12"
headerStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Brown)
For k = 1 To dgv.Columns.Count
xlWorkSheet.Cells(4, k) = dgv.Columns(k - 1).HeaderText
xlWorkSheet.Cells(4, k).Style = "NewStyle"
Next
'=======================================================================================================
Dim str As String = ""
Dim l As Integer = 1
j = 6
Dim amt As Double = 0.0
For i = 0 To dgv.RowCount - 1
amt = amt + dgv.Rows(i).Cells(4).Value
For m = 0 To dgv.ColumnCount - 1
xlWorkSheet.Cells(j, l) = dgv(m, i).Value.ToString()
str = dgv(m, i).Value.ToString()
l = l + 1
Next
j = j + 1
l = 1
Next
'======================================================================================================
Dim lastStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle2")
lastStyle.Font.Bold = True
lastStyle.Font.Size = "12"
lastStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)
Dim c As Integer = dgv.ColumnCount
xlWorkSheet.Cells(j + 2, c - 1) = "Total Amount"
xlWorkSheet.Cells(j + 2, c) = amt.ToString
xlWorkSheet.Cells(j + 2, c - 1).Style = "NewStyle2"
xlWorkSheet.Cells(j + 2, c).Style = "NewStyle2"
'=======================================================================================================
xlWorkSheet.SaveAs(filepath1 + "\EmployeePaymentReport.xlsx")
xlWorkBook.Close()
xlApp.Quit()
cls.releaseObject(xlApp)
cls.releaseObject(xlWorkBook)
cls.releaseObject(xlWorkSheet)
MsgBox("You can find the file at " + filepath1 + "\EmployeePaymentReport.xlsx")
Catch ex As Exception
MsgBox(ex.Message)
For Each Process In System.Diagnostics.Process.GetProcessesByName("EXCEL")
If Process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE") Then
Process.Kill()
End If
Next
End Try
Else
Exit Sub
End If
Catch ex As Exception
End Try
End Sub

VB export listview to Excel

I keep getting 'Exception from HRESULT: 0x800A03EC' error when I run my code.
Some forums say that the '1' needs to be changed to a '0' or vice versa.
At this point I just don't know what is wrong nothing is sticking out. I believe I have all the references loaded that I need, so any suggestions/help would be much appreciated.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim objExcel As New Excel.Application
Dim bkWorkBook As Workbook
Dim shWorkSheet As Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = bkWorkBook.ActiveSheet
For i = 0 To Me.ListView1.Columns.Count
shWorkSheet.Cells(1, Chr(64 + i)) = Me.ListView1.Columns(i)
Next
For i = 1 To Me.ListView1.Items.Count
shWorkSheet.Cells(i + 2, "A") = Me.ListView1.Items(i).Text
For j = 2 To Me.ListView1.Items.Count
shWorkSheet.Cells(i + 2, Chr(64 + j)) = Me.ListView1.Items(i).SubItems(j - 1)
Next
Next
objExcel.Visible = True
End Sub
Thanks,
I retested and found I hadn't fully tested a listview with more than a couple of columns. Try this:
Try
Dim objExcel As New Excel.Application
Dim bkWorkBook As Workbook
Dim shWorkSheet As Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = CType(bkWorkBook.ActiveSheet, Worksheet)
For i = 0 To Me.ListView1.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = Me.ListView1.Columns(i).Text
Next
For i = 0 To Me.ListView1.Items.Count - 1
For j = 0 To Me.ListView1.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = Me.ListView1.Items(i).SubItems(j).Text
Next
Next
objExcel.Visible = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
shWorkSheet.Cells(1, Chr(64 + i))
should be
shWorkSheet.Cells(1, i)
Cells expects one or two numeric arguments.
This code only add : CreateObject and autofiT rows and columns
Public Sub ExportLw2Excel(Lw As ListView)
Try
Dim objExcel As Object ' New Excel.Application
objExcel = CreateObject("Excel.Application")
Dim bkWorkBook As Object 'As Workbook
Dim shWorkSheet As Object 'As Worksheet
Dim i As Integer
Dim j As Integer
'objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = bkWorkBook.activesheet ' CType(bkWorkBook.ActiveSheet, Worksheet)
For i = 0 To Lw.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = Lw.Columns(i).Text
Next
For i = 0 To Lw.Items.Count - 1
For j = 0 To Lw.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = Lw.Items(i).SubItems(j).Text
Next
Next
objExcel.Cells.Select
objExcel.Cells.EntireColumn.AutoFit
objExcel.Cells.EntireRow.AutoFit
objExcel.Range("A1:B1").Select
objExcel.Selection.Font.Bold = True
objExcel.Range("A1").Select
objExcel.Visible = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This is a solution if you want to export your listview with colored lines to Excel. Please position the indexes correctly according to your ListViews Rows and Columns indexes!!
Try
Dim objExcel As New Excel.Application
Dim bkWorkBook As Excel.Workbook
Dim shWorkSheet As Excel.Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = CType(bkWorkBook.ActiveSheet, Excel.Worksheet)
For i = 0 To objLv.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = objLv.Columns(i).Text
Next
For i = 0 To objLv.Items.Count - 1
Dim clr = ColorTranslator.ToOle(objLv.Items(i - 1).BackColor)
shWorkSheet.Rows(i).Interior.Color = clr
For j = 2 To objLv.Columns.Count
shWorkSheet.Cells(i + 1, j - 1).Value = objLv.Items(i - 1).SubItems(j - 1).Text
Next
Next
objExcel.Visible = True
Catch ex As Exception
MsgBox(ex.Message)
End Try