这不是它的工作原理。如果你这样做,文件将保存在 sql server 上。
你需要做
select * from your_table
到数据表中。然后使用 FileHelpers Library 创建一个 csv 文件:
FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
然后将此 csv 文件写入 HttpContext.Response 并设置附加标头。
Public Class TextHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World!")
Dim memoryStream As New System.IO.MemoryStream()
Dim textWriter As System.IO.TextWriter = New System.IO.StreamWriter(memoryStream)
textWriter.WriteLine("YOUR CSV CONTENT")
textWriter.Flush()
memoryStream.Position = 0
Dim bytesInStream As Byte() = New Byte(memoryStream.Length - 1) {}
'memoryStream.Write(bytesInStream, 0, bytesInStream.Length)
memoryStream.Read(bytesInStream, 0, CInt(memoryStream.Length))
memoryStream.Close()
context.Response.Clear()
context.Response.ContentType = "application/octet-stream"
context.Response.AddHeader("Content-Disposition", GetContentDisposition(strFileName))
context.Response.BinaryWrite(bytesInStream)
context.Response.End()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Public Shared Function StripInvalidPathChars(str As String) As String
If str Is Nothing Then
Return Nothing
End If
Dim strReturnValue As String = ""
Dim strInvalidPathChars As New String(System.IO.Path.GetInvalidPathChars())
Dim bIsValid As Boolean = True
For Each cThisChar As Char In str
bIsValid = True
For Each cInvalid As Char In strInvalidPathChars
If cThisChar = cInvalid Then
bIsValid = False
Exit For
End If
Next cInvalid
If bIsValid Then
strReturnValue += cThisChar
End If
Next cThisChar
Return strReturnValue
End Function ' StripInvalidPathChars
Public Shared Function GetContentDisposition(ByVal strFileName As String) As String
' http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http
Dim contentDisposition As String
strFileName = StripInvalidPathChars(strFileName)
If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.Request.Browser IsNot Nothing Then
If (System.Web.HttpContext.Current.Request.Browser.Browser = "IE" And (System.Web.HttpContext.Current.Request.Browser.Version = "7.0" Or System.Web.HttpContext.Current.Request.Browser.Version = "8.0")) Then
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(strFileName).Replace("'", Uri.HexEscape("'"c))
ElseIf (System.Web.HttpContext.Current.Request.Browser.Browser = "Safari") Then
contentDisposition = "attachment; filename=" + strFileName
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Return contentDisposition
End Function ' GetContentDisposition
由于 CSV 是纯文本,您可能只需设置 ContentType、附加 + 将文本直接写入响应,而不使用 MemoryStream。