How to fix InvalidArgument= Value of '3' is not valid for 'index'. Parameter name: index in exporting listview items to excel - vb.net-2010

I'm setting up a program, and want to save my listview items to Excel, but there's always an error in saving my items.
I;m using Windows 7 and Visual Basic 2010. There are actually 3 columns, and an unexpected number of rows since I'm running a food menu program, so the number of subitems are unexpected.
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button13.Click
Try
Me.Cursor = Cursors.WaitCursor
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For i = 1 To Me.ListView1.Items.Count
.cells(i, 1) = Me.ListView1.Items(i - 1).Text
For j = 1 To ListView1.Columns.Count - 1
.cells(i, j + 1) = Me.ListView1.Items(i - 1).SubItems(j).Text
Next
Next
End With
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
Exit Sub
End Sub
I expect it to display on the Excel program with the following listview items, but there's just an error, so it can't proceed.

Please try the below updated code:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Try
Me.Cursor = Cursors.WaitCursor
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For i = 0 To Me.ListView1.Columns.Count - 1
.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
.cells(i + 2, j + 1) = Me.ListView1.Items(i).SubItems(j).Text
Next
Next
End With
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
Exit Sub
End Sub

Related

Export DataGridView to Excel using VB 2013

Im fairly new to VB 2013. Any advice and help is greatly appreciated.
I have a datagridview that I want to export to Excel. I have the code working that does the export, but it doesnt show the header names. I need to edit the code to bring the header names over as well.
Additionally, I want to drop the first column from the export.
Example of my gridview code:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
'Export Header Names Start
Dim columnsCount As Integer = DataGridView1.Columns.Count
For Each column In DataGridView1.Columns
xlWorkSheet.Cells(1, column.Index + 1).Value = column.name
Next
' 'Export Header Name End
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
If System.IO.File.Exists("C:\test\export.xlsx") Then
System.IO.File.Delete("C:\test\export.xlsx")
End If
xlWorkSheet.SaveAs("C:\test\export.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file here C:\test")
End Sub
DataGridview Output:
For many years i,m using this function.
Public Sub grid_ToExcel_Export(ByVal FileName As String, ByVal Data_GridView As DataGridView)
Dim sb As New System.Text.StringBuilder
Try
Dim intColumn, intColumnValue As Integer
Dim row As DataGridViewRow
For intColumn = 0 To Data_GridView.Columns.Count - 1
sb.Append(Data_GridView.Columns(intColumn).HeaderText)
If intColumnValue <> Data_GridView.Columns.Count - 1 Then
sb.Append(vbTab)
End If
Next
sb.Append(vbCrLf)
For Each row In Data_GridView.Rows
For intColumnValue = 0 To Data_GridView.Columns.Count - 1
sb.Append(StrConv(IIf(IsDBNull(row.Cells(intColumnValue).Value), "", row.Cells(intColumnValue).Value), VbStrConv.None))
If intColumnValue <> Data_GridView.Columns.Count - 1 Then
sb.Append(vbTab)
End If
Next
sb.Append(vbCrLf)
Next
SaveExcel(FileName, sb)
Catch ex As Exception
Throw
Finally
Data_GridView = Nothing
sb = Nothing
End Try
End Sub
Private Sub SaveExcel(ByVal fpath As String, ByVal sb As System.Text.StringBuilder)
Dim fsFile As New FileStream(fpath, FileMode.Create, FileAccess.Write)
Dim strWriter As New StreamWriter(fsFile, System.Text.Encoding.Unicode)
Try
With strWriter
.BaseStream.Seek(0, SeekOrigin.End)
.WriteLine(sb)
.Close()
End With
Catch e As Exception
msg(e.ToString)
Finally
sb = Nothing
strWriter = Nothing
fsFile = Nothing
End Try
End Sub

Try statement not catching the exception vb.net

My exception isn't working for an excel file that is searched and returned with information. Below you will see that it cycles through the first column and returns information according to variables that are set globally. I have put an exception that if the try fails a message box will pop up and tell them it failed to find them, but its not catching it. Instead if the user isn't listed in the database it freezes the program.
Private Sub ExceptionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExceptionToolStripMenuItem.Click
Dim objexcel As New Excel.Application
Dim objWorkbook As Excel.Workbook
Dim objWorksheet As Excel.Worksheet
objexcel.DisplayAlerts = False
If Global_Variables.SavedResults.UserM = Nothing And Global_Variables.SavedResults.UserL = Nothing Then
objWorkbook = objexcel.Workbooks.Open("filepath", [ReadOnly]:=True)
objWorksheet = CType(objWorkbook.Worksheets.Item("Sheet1"), Excel.Worksheet)
Try
For x As Integer = 1 To objWorksheet.Rows.Count Step 1
If objWorksheet.Cells(x, 1).value = Global_Variables.SavedResults.UserD Then
Global_Variables.SavedResults.UserL = objWorksheet.Cells(x, 3).value
Global_Variables.SavedResults.UserM = objWorksheet.Cells(x, 2).value
Exit For
End If
Next
Exit Try
Catch ex As Exception
MsgBox("You are not in the Database.")
End Try
objWorkbook.Close()
objexcel.Quit()
ReleaseObject(objWorksheet)
ReleaseObject(objWorkbook)
ReleaseObject(objexcel)
objWorkbook = Nothing
objWorksheet = Nothing
objexcel = Nothing
End If
Dim Email As New Email_Templates
Email.Exception()
End Sub

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

Formating excel spread sheet export from multiple datagridviews 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

Export to excel vb.net

I have a problem when I export a flexgrid to excel from vb.net vs2008 to office 2010 english version an excel file is opened but it is empty. However, when I use office french version it is opened [correctly]
My code is:
On Error GoTo ErrorHandler
Dim iRow As Short
Dim iCol As Short
Dim objExcl As Excel.Application
Dim objWk As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim iHead As Short
Dim vHead As Object
objExcl = New Excel.Application
objExcl.Visible = True
objExcl.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")
objWk = objExcl.Workbooks.Add
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
objSht = objWk.Sheets(1)
vHead = Split(g.FormatString, "|")
'populate heading in the sheet
'take the column heading from flex grid and put it in the sheet
For iHead = 1 To UBound(vHead)
If Len(Trim(vHead(iHead))) > 0 Then objSht.Cells._Default(1, iHead) = vHead(iHead)
Next
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
For iRow = 0 To g.Rows - 1
For iCol = 0 To g.get_Cols() - 1
g.Row = iRow
g.Col = iCol
'
'If g.Text <> "" Then objSht.Cells._Default(iRow + 2, iCol + 1) = g.Text
If g.Text <> "" Then
objSht.Range(NumCol2Lattre(iCol + 1) & "" & iRow + 2 & ":" & NumCol2Lattre(iCol + 1) & "" & iRow + 2 & "").Select()
objExcl.ActiveCell.Value = g.Text
End If
Next iCol
Next iRow
objExcl.Application.Visible = True
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
objSht = Nothing
objWk = Nothingl may not be destroyed until it is garbage collected. Click
objExcl = Nothing
Exit Sub
ErrorHandler:
objSht = Nothing
objWk = Nothing
objExcl = Nothing
MsgBox("Error In expotation task & " & Err.Description, MsgBoxStyle.Information)
Err.Clear()
Check out this website Exporting MSFlexGrid to Excel
I suspect your problem is with vHead = Split(g.FormatString, "|") Use the debugger to find out what is the value of g.FormatString. Is it causing an error? Step through the code one line at a time and see what happens.
On Error GoTo ErrorHandler
Imports System.Data
Imports System.IO
Imports System.Web.UI
Partial Class ExportGridviewDatainVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
dt.Rows.Add(1, "SureshDasari", "B.Tech", "Chennai")
dt.Rows.Add(2, "MadhavSai", "MBA", "Nagpur")
dt.Rows.Add(3, "MaheshDasari", "B.Tech", "Nuzividu")
dt.Rows.Add(4, "Rohini", "MSC", "Chennai")
dt.Rows.Add(5, "Mahendra", "CA", "Guntur")
dt.Rows.Add(6, "Honey", "B.Tech", "Nagpur")
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gvDetails.AllowPaging = False
BindGridview()
'Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF")
'Applying stlye to gridview header cells
For i As Integer = 0 To gvDetails.HeaderRow.Cells.Count - 1
gvDetails.HeaderRow.Cells(i).Style.Add("background-color", "#df5015")
Next
gvDetails.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
End Class