Formating excel spread sheet export from multiple datagridviews vb.net - vb.net

I am currently working in microsoft visual studio 2013 with an sql back end. I am loading multiple DGVs' and then trying to export them to an excel spread sheet. However, I am not sure how to format this data. When I try and export multiple DGVs' they write over top of each other in the top left hand corner of the excel file. Does anyone know how to format and select where you want the DGVs' to load on the excel spreadsheet. I don't want them all to be on different sheets either. Here is my code:
Private Sub BtnExcelExport_Click(sender As Object, e As EventArgs) Handles BtnExcelExport.Click
Try
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.Application
xlworkbook = xlapp.Workbooks.Add(misvalue)
xlworksheet = xlworkbook.Sheets("sheet1")
For I = 0 To DGVJobs.RowCount - 1
For J = 0 To DGVJobs.ColumnCount - 1
For K As Integer = 1 To DGVJobs.Columns.Count
xlworksheet.Cells(1, K) = DGVJobs.Columns(K - 1).HeaderText
xlworksheet.Cells(I + 2, J + 1) = DGVJobs(J, I).Value.ToString()
Next
Next
Next
'Here is my second DGV upload out of a few, this one will write over top of the other
For I = 0 To DGVAssociates.RowCount - 1
For J = 0 To DGVAssociates.ColumnCount - 1
For K As Integer = 1 To DGVAssociates.Columns.Count
xlworksheet.Cells(1, K) = DGVAssociates.Columns(K - 1).HeaderText
xlworksheet.Cells(I + 2, J + 1) = DGVAssociates(J, I).Value.ToString()
Next
Next
Next
xlworksheet.SaveAs("C:\example.xlsx")
xlworkbook.Close()
xlapp.Quit()
releaseobject(xlapp)
releaseobject(xlworkbook)
releaseobject(xlworksheet)
MsgBox("You can find the file C:\example.xlsx")
Dim res As MsgBoxResult
res = MsgBox("Saving completed, would you like to open the file?", MsgBoxStyle.YesNo)
If (res = MsgBoxResult.Yes) Then
Process.Start("C:\example.xlsx")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
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
The second for loop is where I am having the over-write problem. If anyone has a link that can send me to a good website please post it as well.

Why are you looping twice throuhg the columns? The most inner loop is unnecesary.
Now, the variables you're using to specify the column to write to in excel go from 0 to ColumnCount in both groups of Fors. That's why they're overwriting each other.
Try this:
For I = 0 To DGVJobs.RowCount - 1
For J = 0 To DGVJobs.ColumnCount - 1
xlworksheet.Cells(1, J + 1) = DGVJobs.Columns(J).HeaderText
xlworksheet.Cells(I + 2, J + 1) = DGVJobs(J, I).Value.ToString()
Next
Next
For I = 0 To DGVAssociates.RowCount - 1
For J = 0 To DGVAssociates.ColumnCount - 1
xlworksheet.Cells(1, J + 1 + DGVJobs.ColumnCount) = DGVAssociates.Columns(K - 1).HeaderText
xlworksheet.Cells(I + 2, J + 1 + DGVJobs.ColumnCount) = DGVAssociates(J, I).Value.ToString()
Next
Next
(BTW and off-topic; a faster way to export data to excel is to first create an array with all the data and then asign it to the corresponding Range in the worksheet)

Try This Code, Then You Will Surely Text Me a Message of Thanks :)
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.IO
Private Sub ExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportToExcel.Click
Try
Dim xlapp As Microsoft.Office.Interop.Excel.Application
Dim xlworkbook As Microsoft.Office.Interop.Excel.Workbook
Dim xlworksheet, xlworksheet1 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.Application
xlworkbook = xlapp.Workbooks.Add(misvalue)
xlworksheet = xlworkbook.Sheets("Sheet1")
For I = 0 To DataGridView_Report.RowCount - 1
For J = 0 To DataGridView_Report.ColumnCount - 1
For K As Integer = 1 To DataGridView_Report.Columns.Count
xlworksheet.Cells(1, K) = DataGridView_Report.Columns(K - 1).HeaderText
xlworksheet.Cells(I + 2, J + 1) = DataGridView_Report(J, I).Value.ToString()
Next
Next
Next
xlworksheet1 = CType(xlworkbook.Worksheets.Add(), Excel.Worksheet)
For I = 0 To DataGridView_Calculation.RowCount - 1
For J = 0 To DataGridView_Calculation.ColumnCount - 1
For K As Integer = 1 To DataGridView_Calculation.Columns.Count
xlworksheet1.Cells(1, K) = DataGridView_Calculation.Columns(K - 1).HeaderText
xlworksheet1.Cells(I + 2, J + 1) = DataGridView_Calculation(J, I).Value.ToString()
Next
Next
Next
xlworksheet.Columns.AutoFit()
xlworksheet1.Columns.AutoFit()
Dim xlRange, xlRange1 As Excel.Range
xlRange = xlworksheet.Range("A1", "N1")
xlRange1 = xlworksheet1.Range("A1", "L1")
xlRange.Columns.Font.Bold = True
xlRange1.Columns.Font.Bold = True
xlworksheet.Name = "My Sheet1"
xlworksheet1.Name = "My Sheet2"
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Excel Workbook|*.xls|Excel Workbook 2011|*.xlsx"
saveFileDialog1.Title = "Save Excel File"
saveFileDialog1.FileName = "Export " & Now.ToShortDateString & ".xlsx"
saveFileDialog1.ShowDialog()
saveFileDialog1.InitialDirectory = "C:/"
If saveFileDialog1.FileName <> "" Then
Dim fs As System.IO.FileStream = CType(saveFileDialog1.OpenFile(), System.IO.FileStream)
fs.Close()
End If
Dim strFileName As String = saveFileDialog1.FileName
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
Exit Sub
End Try
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
xlworkbook.SaveAs(strFileName)
xlapp.Workbooks.Open(strFileName)
xlapp.Visible = True
Exit Sub
errorhandler:
MsgBox(Err.Description)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
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

Related

DataGridView missing last row in the Excel file

So when i try to export my data on datagridview to excel, the last row in the excel file was not included, and here i used datasource to connect the ms.access database. Can you guys help ?
BtnPrint.Click
SaveFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
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.Application
xlworkbook = xlapp.Workbooks.Add(misvalue)
xlworksheet = xlworkbook.Sheets("sheet1")
For i = 0 To SKU2021DataGridView.RowCount - 2
For j = 0 To SKU2021DataGridView.ColumnCount - 1
For k As Integer = 1 To SKU2021DataGridView.Columns.Count
xlworksheet.Cells(1, k) = SKU2021DataGridView.Columns(k - 1).HeaderText
xlworksheet.Cells(i + 2, j + 1) = SKU2021DataGridView(j, i).Value.ToString()
Next
Next
Next
xlworksheet.SaveAs(SaveFileDialog1.FileName)
xlworkbook.Close()
xlapp.Quit()
releaseobject(xlapp)
releaseobject(xlworkbook)
releaseobject(xlworksheet)
MessageBox.Show("Proses Export Berhasil", "Sukses", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
ReleaseObject()
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
Here The Pic of The Excel and WindowForm
Change
For i = 0 To SKU2021DataGridView.RowCount - 2
For j = 0 To SKU2021DataGridView.ColumnCount - 1
For k As Integer = 1 To SKU2021DataGridView.Columns.Count
xlworksheet.Cells(1, k) = SKU2021DataGridView.Columns(k - 1).HeaderText
xlworksheet.Cells(i + 2, j + 1) = SKU2021DataGridView(j, i).Value.ToString()
Next
Next
Next
To
For i = 0 To SKU2021DataGridView.RowCount - 1
For j = 0 To SKU2021DataGridView.ColumnCount - 1
For k As Integer = 1 To SKU2021DataGridView.Columns.Count
xlworksheet.Cells(1, k) = SKU2021DataGridView.Columns(k - 1).HeaderText
Next
xlworksheet.Cells(i + 2, j + 1) = SKU2021DataGridView(j, i).Value.ToString()
Next
Next

Does not export datagridview data to excel vb.net

Im exporting a datagridview to excel, when I export the rows that contains data only for one year it works very well, but when I do for 2 or more years It does not export, my winform collapse.In total, I have 135159 rows to export.
this is my code
Dim exApp As New Microsoft.Office.Interop.Excel.Application
Dim exLibro As Microsoft.Office.Interop.Excel.Workbook
Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet
Try
exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()
Dim NCol As Integer = dgvDatos.ColumnCount
Dim NRow As Integer = dgvDatos.RowCount
'this is to export columns
For i As Integer = 1 To NCol
exHoja.Cells.Item(1, i) = dgvDatos.Columns(i - 1).Name.ToString
Next
'this is to export all the rows
For Fila As Integer = 0 To NRow - 1
For Col As Integer = 0 To NCol - 1
exHoja.Cells.Item(Fila + 2, Col + 1) = dgvDatos.Item(Col, Fila).Value
Next
Next
It would be great if you could help me, Thankss!!
Try this code:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.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.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'FOR HEADERS
For i = 1 To DataGridView1.ColumnCount
xlWorkSheet.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
'FOR ITEMS
For j = 1 To DataGridView1.RowCount
xlWorkSheet.Cells(j + 1, i) = DataGridView1(i - 1, j - 1).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file D:\vbexcel.xlsx")
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
End Class
The path is in the D: and the file name is vbexcel.xlsx
Note: choosing No will get an error cause it will replace the file with the same file name in the same path. Always choose Yes to replace the existing file.

Exporting all records from datagridview to Excel VB.NET

I used this code to export my records to excel and it works fine, but it only exports one row. Is there anyway to record all my data in the datagridview? Also, I'm not familiar with crystal report in VB so I want to use a button click event..
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 = xlWorkBook.Sheets("sheet1")
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()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file D:\vbexcel.xlsx")
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
I can't comment to the one who posted this code cause I have few reputation...
Change your For Loop.
'FOR HEADERS
For i = 1 To DataGridView1.ColumnCount
xlWorkSheet.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
'FOR ITEMS
For j = 1 To DataGridView1.RowCount
xlWorkSheet.Cells(j + 1, i) = DataGridView1(i - 1, j - 1).Value.ToString()
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

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