Private constringconnect As String = ConfigurationManager.ConnectionStrings("smeorgConnectionString").ConnectionString.ToString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
createExcel()
End If
End Sub
Private Function getdate() As DataSet
Dim con As New System.Data.SqlClient.SqlConnection(constringconnect)
Dim cmd As New System.Data.SqlClient.SqlDataAdapter("SELECT top 50 * FROM Table_1", con)
con.Open()
Dim myds As New DataSet()
cmd.Fill(myds)
con.Close()
cmd.Dispose()
Return myds
End Function
Private Sub createExcel()
Dim ds As DataSet = getdate()
Dim exce As New Excel.Application() '需要添加EXCEL.exe引用
Dim rowindex As Integer = 1
Dim collindex As Integer = 0
exce.Application.Workbooks.Add(True) '添加EXCEL对象的工作表
Dim tabel As System.Data.DataTable = ds.Tables(0)
For Each col As DataColumn In tabel.Columns '将所得表的列名,赋值给单元格
collindex = collindex + 1
exce.Cells(1, collindex) = col.ColumnName
Next
For Each row As DataRow In tabel.Rows'取得所得表的,数据行
rowindex = rowindex + 1
collindex = 0
For Each col As DataColumn In tabel.Columns
collindex = collindex + 1
exce.Cells(rowindex, collindex) = row(col.ColumnName).ToString
Next
Next
exce.Visible = False'隐藏后台处理
exce.DisplayAlerts = False
exce.Save(MapPath("excel/Excel.xls"))
exce.Application.Workbooks.Close()
exce.Quit()
//释放使用的EXCEL对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(exce)
GC.Collect()'调用垃圾收集内存
End Sub