Send excel file to user in web

Private Sub ExportFile(ByVal strfilePath As String, ByVal strFilename As String)
Try
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
strfilePath = Server.MapPath(strfilePath)
If Not System.IO.File.Exists(strfilePath) Then
strfilePath = Server.MapPath("~//Data//ExportToExcel//NoRecord.xls")
Response.AddHeader("content-disposition", ("attachment;filename=" + ("NoRecord" + ".xls")))
Else
Response.AddHeader("content-disposition", ("attachment;filename=" _
+ (strFilename + ".xls")))
End If

        Dim sourcefile As FileStream = New FileStream(strfilePath, FileMode.Open)
        Dim filesize As Long
        filesize = sourcefile.Length
        Dim getcontent() As Byte = New Byte((CType(filesize, Integer)) - 1) {}
        sourcefile.Read(getcontent, 0, CType(sourcefile.Length, Integer))
        sourcefile.Close()
        Response.BinaryWrite(getcontent)
    Catch ex As Exception
        ex = ex
    Finally
        Response.End()
    End Try

End Sub

Subscribe to Code, Query, Ship, and Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe