Private
Sub Btn_Exe_Click()
Sub Btn_Exe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Exe.Click
Dim connStr As String = "Data Source=(local); Database=pubs; Integrated Security=SSPI;"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comStr As String = "select * from authors"
Dim da As SqlDataAdapter = New SqlDataAdapter(comStr, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "table1")
DataGridView1.DataSource = ds.Tables("table1")
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
Me.Cursor = Cursors.WaitCursor
Dim myExcel As excel.Application = New excel.Application
myExcel.Application.Workbooks.Add(True)
myExcel.Visible = True
Dim i As Integer
For i = 0 To ds.Tables("table1").Columns.Count - 1
myExcel.Cells(1, i + 1) = ds.Tables("table1").Columns(i).Caption
Next
Dim m, n As Integer
For m = 0 To ds.Tables("table1").Rows.Count - 1
For n = 0 To ds.Tables("table1").Columns.Count - 1
myExcel.Cells(m + 2, n + 1) = ds.Tables("table1").Rows(m)(n).ToString
Next
Next
Me.Cursor = Cursors.Default
Dim connStr As String = "Data Source=(local); Database=pubs; Integrated Security=SSPI;"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comStr As String = "select * from authors"
Dim da As SqlDataAdapter = New SqlDataAdapter(comStr, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "table1")
DataGridView1.DataSource = ds.Tables("table1")
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
Me.Cursor = Cursors.WaitCursor
Dim myExcel As excel.Application = New excel.Application
myExcel.Application.Workbooks.Add(True)
myExcel.Visible = True
Dim i As Integer
For i = 0 To ds.Tables("table1").Columns.Count - 1
myExcel.Cells(1, i + 1) = ds.Tables("table1").Columns(i).Caption
Next
Dim m, n As Integer
For m = 0 To ds.Tables("table1").Rows.Count - 1
For n = 0 To ds.Tables("table1").Columns.Count - 1
myExcel.Cells(m + 2, n + 1) = ds.Tables("table1").Rows(m)(n).ToString
Next
Next
Me.Cursor = Cursors.Default
myExcel.Application.ActiveWorkbook.SaveAs("E:/test.xls")
MsgBox("Export Successful!")
End Sub
MsgBox("Export Successful!")
End Sub