Dim conn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(ConfigurationSettings.AppSettings.Item("conn"))
        Dim cmd As Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand("抓取資料的SQL句", conn)
        conn.Open()
        Dim filename As String = Server.MapPath("GetExcel.xls")
        Dim dr As Data.SqlClient.SqlDataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
        Dim sw As IO.StreamWriter = New IO.StreamWriter(filename, False, System.Text.Encoding.Default)
        Do While dr.Read()
            For i As Integer = 0 To dr.FieldCount - 1
                sw.Write(dr(i) & vbTab)
            Next
            sw.WriteLine()
        Loop
        sw.Close()
        dr.Close()

        Response.AddHeader("Content-Disposition", "attachment;filename=GetExcel.xls")
        Response.ContentType = "application/vnd.ms-excel"
        Response.WriteFile(filename)
        Response.End()

goodlucky 發表在 痞客邦 PIXNET 留言(0) 人氣()