0

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

enter image description here

Alexandra
  • 65
  • 1
  • 2
  • 13
  • I have already looked at this article: [Export data to Excel in Webmatrix](http://www.codeproject.com/Articles/388292/Export-data-to-Excel-in-Webmatrix)? – GmG Jul 01 '13 at 21:18
  • This is what I want to do but I cannot get the code to work, I have never worked on ASP can you show me an example of how you got yours to work please? – Alexandra Jul 08 '13 at 14:02

1 Answers1

0

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.

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • I downloaded filehelpers and it is now installed. Now I am having a bit of trouble with the setup can you guide me a bit or show me an example please? Thank you so much – Alexandra Jul 01 '13 at 13:46
  • You need to add the FileHelpers.dll library as reference. Then in server-side code, you do FileHelpers.CsvEngine.DataTableToCsv(dt, "filename") – Stefan Steiger Jul 01 '13 at 13:55