大家好,我试图让用户从数据库中下载数据,这样他们就可以在没有访问数据库的情况下对其进行操作。到目前为止,我有这个文件,但我需要将它下载到客户端电脑。有小费吗?
Protected Sub ExportDataTableToCSV(cmdText As String)
Try
Dim sqlcon_Local As New SqlClient.SqlConnection
sqlcon_Local.ConnectionString = ConfigurationManager.ConnectionStrings("Portal").ConnectionString
Dim objCmd As New SqlCommand(cmdText, sqlcon_Local)
Dim da As SqlDataAdapter = New SqlDataAdapter(objCmd)
Dim dt As DataTable = New DataTable
da.Fill(dt)
Dim filename As String = Server.MapPath("~/download.csv")
Dim sw As New StreamWriter(filename, False)
Dim iColCount As Integer = dt.Columns.Count
For i As Integer = 0 To iColCount - 1
sw.Write(dt.Columns(i))
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()
Response.Clear()
Response.ContentType = "application/csv"
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv")
Response.WriteFile(filename)
Response.Flush()
Response.End()
Catch ex As Exception
End Try
End Sub
我究竟做错了什么?欢迎任何意见。
谢谢你的时间!