简体   繁体   中英

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. 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. 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.

You need to do

select * from your_table 

into a datatable. Then you use the FileHelpers Library to create a csv file:

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);

Then you write this csv-file to HttpContext.Response and set the attach header.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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