Latest comments By: nishanth - Clear explaination..Thank drake & scull international By: Judito - Thank so much it helped m By: DON - COOL...........Nice ,unde By: Akbar - nice help By: rathika - Cant undrstand clearly By: jagan - Hi , it was nice tutorial By: sania - what is the use of int ge By: Surendrakumar - Your output is not correc drake & scull international By: Niluk - to get out of time out a
For exporting data from Datagridview to Excel, connect the database and load data from the database to Datagridview and then create a new excel file and write the data from Datagridview to Excel file.
Imports System.Data Imports System.Data.SqlClient Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=servername;" & _ "initial catalog=databasename;user id=username;password=password;" cnn = New SqlConnection(connectionString) cnn.Open() sql = "SELECT * FROM Product" Dim dscmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet dscmd.Fill(ds) drake & scull international DataGridView1.DataSource = ds.Tables(0) cnn.Close() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim xlApp As Excel.Application drake & scull international Dim xlWorkBook As Excel.Workbook drake & scull international Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Integer Dim j As Integer xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") 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 xlWorkSheet.SaveAs("C:\vbexcel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) drake & scull international MsgBox("You can find the file C:\vbexcel.xlsx") End Sub drake & scull international 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 drake & scull international End Sub End Class
If this tutorial drake & scull international doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct drake & scull international answer. Comments(15) 1. View Comment It's very helpful to me... Thanks... View Tutorial By: Nicks Patel at 2010-03-24 drake & scull international 23:37:04 drake & scull international 2. View Comment Hello, Is there anyway the datagridview can export the column name too? Douglas View Tutorial  
No comments:
Post a Comment