简体   繁体   English

如何将查询数据库中的数据导出到SQL中的excel

[英]how to export the data from a queried database to excel in SQL

I have a page where a database is filtered by many factors: Name, Id, Status, etc. I want to be able to press a button that says "Open this query in excel" and it will download the results into excel. 我有一个页面,其中按许多因素过滤了数据库:名称,ID,状态等。我希望能够按下显示“在excel中打开此查询”的按钮,并将其下载到excel中。 How is this possible? 这怎么可能? I have seen something like this: 我看过这样的东西:

"SELECT * INTO OUTFILE 'query.csv' FROM RMS WHERE 1 = '1'";

But this is not working for me. 但这对我不起作用。 I already have the database querying right, I just need the functionality to export that query to excel by pressing a button that will download the complete query into an excel file. 我已经拥有数据库查询权,我只需要通过将按钮将完整的查询下载到excel文件中的功能,即可将该查询导出到excel。 If someone could help I will really appreciate it! 如果有人可以帮助我,我将非常感激!

This is how the page looks 这是页面的外观

在此处输入图片说明

That's not how it works. 那不是它的工作原理。 If you do it that way, the file gets saved on the sql server. 如果这样做,该文件将保存在sql服务器上。

You need to do 你需要做

select * from your_table 

into a datatable. 到数据表中 Then you use the FileHelpers Library to create a csv file: 然后,使用FileHelpers库创建一个csv文件:

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);

Then you write this csv-file to HttpContext.Response and set the attach header. 然后,将此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

Since CSV is plain text, you could probably just set the ContentType, Attach + write the text to the Response directly, without using MemoryStream. 由于CSV是纯文本,因此您可能只需要设置ContentType,直接将文本附加+写到响应中,而无需使用MemoryStream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM