hi, I'm new to Vb.net and I need a little help. I have this Code to Export All Data from Datagridview to Excel and it works well, Problem 1 :
But what I want to do is To export only Specific columns, not all columns from Datagridview (Example I want to Export only Column 3 and 5) Not all Columns.
And Problem 2:
is It is possible to export in an existing template example I have an excel template with Name And ID to export in this existing template not in new.
Thank You.
Code:' Creating a Excel object. 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 Try worksheet = workbook.ActiveSheet 'worksheet.Name = "ExportedFromDatGrid" ' worksheet.Name = Me.Text ' Dim cellRowIndex As Integer = 1 Dim cellColumnIndex As Integer = 1 'Loop through each row and read value from each column. For i As Integer = -1 To dgw.Rows.Count - 1 For j As Integer = 0 To dgw.Columns.Count - 1 ' Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. If cellRowIndex = 1 Then worksheet.Cells(cellRowIndex, cellColumnIndex) = dgw.Columns(j).HeaderText Else worksheet.Cells(cellRowIndex, cellColumnIndex) = dgw.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() saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*" saveDialog.FilterIndex = 2 If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then workbook.SaveAs(saveDialog.FileName) MsgBox("Export Successful", vbInformation) End If Catch ex As System.Exception MessageBox.Show(ex.Message) 'e paraqet probleim ne mesazh Finally excel.Quit() workbook = Nothing excel = Nothing End Try




Reply With Quote
