R
Ryan Lashway
Guest
I am using the below code to export datagridview results to excel, but am getting an error if a cell is null. As long as all cells have values the code works fine.
Any help is appreciated.
Private Sub tsDropDown_btn_Excel_Click(sender as Object, e as EventArgs) handles tsDropDown_btn_Excel.Click
Dim rowCount as Integer = dgview_MemberInfo.Rows.Count
Dim columnCount as Integer = dgview_MemberInfo.Columns.GetColumnCount(DataGridViewElementStates.Display)
Dim misValue as Object = System.Reflection.Missing.Value
Dim i, j as Integer
Dim xlApp as Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook as Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Add(misValue)
Dim xlWorkSheet as Microsoft.Office.Interop.Excel.Worksheet = xlWorkBook.Sheets("sheet1")
for i = 0 To rowCount - 1
for j = 0 to columnCount
xlWorkSheet.Cells(1, k) = dgview_MemberInfo.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = dgview_MemberInfo(j, i).Value.ToString()
Next
Next
xlWorkSheet.Column.AutoFit()
using sfd as New SaveFileDialog
sfd.DefaultExt = "xlsx"
sfd.AddExtenstion = True
sfd.Filter = "Microsoft Excel | *.xlsx"
If sfd.ShowDialog() = DialogResult.OK Then
xlWorkSheet.SaveAs(sfd.FileName)
End If
End Using
xlWorkbook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
Continue reading...
Any help is appreciated.
Private Sub tsDropDown_btn_Excel_Click(sender as Object, e as EventArgs) handles tsDropDown_btn_Excel.Click
Dim rowCount as Integer = dgview_MemberInfo.Rows.Count
Dim columnCount as Integer = dgview_MemberInfo.Columns.GetColumnCount(DataGridViewElementStates.Display)
Dim misValue as Object = System.Reflection.Missing.Value
Dim i, j as Integer
Dim xlApp as Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook as Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Add(misValue)
Dim xlWorkSheet as Microsoft.Office.Interop.Excel.Worksheet = xlWorkBook.Sheets("sheet1")
for i = 0 To rowCount - 1
for j = 0 to columnCount
xlWorkSheet.Cells(1, k) = dgview_MemberInfo.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = dgview_MemberInfo(j, i).Value.ToString()
Next
Next
xlWorkSheet.Column.AutoFit()
using sfd as New SaveFileDialog
sfd.DefaultExt = "xlsx"
sfd.AddExtenstion = True
sfd.Filter = "Microsoft Excel | *.xlsx"
If sfd.ShowDialog() = DialogResult.OK Then
xlWorkSheet.SaveAs(sfd.FileName)
End If
End Using
xlWorkbook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
Continue reading...