Follow Below Script :
Private Sub ExportToExcelFromGridview()
Dim excel As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()
Dim workbook As Microsoft.Office.Interop.Excel._Workbook = excel.Workbooks.Open(TemplatePathEmpty)
Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing
Try
worksheet = workbook.ActiveSheet
worksheet.Name = "SUPPLIER"
Dim cellRowIndex As Integer = 2
Dim cellColumnIndex As Integer = 1
''Adding HeaderText From Datagridview
For Each column As DataGridViewColumn In DgvSUPPLIER.Columns
worksheet.Cells(1, column.Index + 1) = column.HeaderText
Next
For i As Integer = 0 To DgvSUPPLIER.Rows.Count - 1
For j As Integer = 0 To DgvSUPPLIER.Columns.Count - 1
If cellRowIndex = 1 Then
worksheet.Cells(cellRowIndex, cellColumnIndex) _
= DgvSUPPLIER.Columns(j).HeaderText
Else
worksheet.Cells(cellRowIndex, cellColumnIndex) _
= DgvSUPPLIER.Rows(i).Cells(j).Value.ToString()
End If
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
'Getting the location and file name of the excel to save from user.
Dim saveDialog As New SaveFileDialog()
With saveDialog
.Title = "SAVE AS"
.FileName = "REMOVED.xlsx"
.Filter = "Type(*.xlsx)|*.xlsx"
End With
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
workbook.SaveAs(saveDialog.FileName)
MsgBox("EXPORT INCORRECT METHOD, SUCCESS !!", vbInformation, Me.Text)
excel.Visible = True
excel = Nothing
workbook = Nothing
LblMESSAGE.Text = ""
LvSUPPLIER.Items.Clear()
DgvSUPPLIER.DataSource = Nothing
DgvSUPPLIER.Rows.Clear()
End If
Catch ex As System.Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Comments
Post a Comment