I'm a newbie to visual studio.
I want to export different datagridviews from multiple forms to an excel workbook as different sheets on the same workbook based on whether it is checked in checkedlist box.
Basically I am doing a daily checklist for our school on location basis where the user can export checklist floor wise on the corresponding form of each floor, but also can export a multiple sheet workbook containing diff floors as per its checked in checklistbox, any help please? I am stuck at checkedlistbox. currently i am doing as below: but gives me an exception at the second sheet.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim excel As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()
Dim workbook As Microsoft.Office.Interop.Excel._Workbook = excel.Workbooks.Add(Type.Missing)
Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing
Me.Cursor = Cursors.WaitCursor
Dim sheetnumber As Integer = 1
If CheckedListBox1.GetItemChecked(0) = True Then
worksheet = workbook.Sheets(sheetnumber)
sheetnumber = sheetnumber + 1
worksheet.Name = "Anim_Check List_"
Dim cellRowIndex As Integer = 1
Dim cellColumnIndex As Integer = 1
For i As Integer = 0 To Form7.DataGridView1.Rows.Count - 1
For j As Integer = 0 To Form7.DataGridView1.Columns.Count - 1
If cellRowIndex = 1 Then
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form7.DataGridView1.Columns(j).HeaderText
Else
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form7.DataGridView1.Rows(i).Cells(j).Value.ToString()
End If
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
End If
If CheckedListBox1.GetItemChecked(1) = True Then
workbook.Worksheets.Add(sheetnumber)
excel.Worksheets(sheetnumber).activate
sheetnumber = sheetnumber + 1
worksheet.Name = "Edits 1-5_"
Dim cellRowIndex As Integer = 1
Dim cellColumnIndex As Integer = 1
For i As Integer = 0 To Form8.DataGridView1.Rows.Count - 1
For j As Integer = 0 To Form8.DataGridView1.Columns.Count - 1
If cellRowIndex = 1 Then
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form8.DataGridView1.Columns(j).HeaderText
Else
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form8.DataGridView1.Rows(i).Cells(j).Value.ToString()
End If
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
End If
Dim saveDialog As New SaveFileDialog()
saveDialog.FileName = workbook.Name
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
saveDialog.FilterIndex = 1
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
workbook.SaveAs(saveDialog.FileName)
MessageBox.Show("Export Successful")
End If
End Sub