ASP.NET - Excel file download, aspx page instead Chrome(works in IE, Firefox)

Asked By Eric Smith on 03-Sep-13 04:04 PM
I have button that users click on my website written in vb.net that downloads an excel file.  No issues with doing this function in IE, Firefox or Opera web browser, but Chrome downloads the .aspx page and not a .xls file.  Doing some research and can't find a solution for far any ideas?

Private Sub WriteDataTableToExcel(ByVal dtBadges As DataTable)
    Dim ErrMsg As String = ""
    Dim dg As New GridView()
    dg.DataSource = dtBadges
    dg.DataBind()
 
    Try
      'doing this to prevent button displaying on Excel documents
      btnDownloadExcel.Text = ""
      btnDownloadExcel.Enabled = False
      btnDownloadExcel.Visible = False
       
      Dim strFileName As String = "WITMeeting.xls"
      HttpContext.Current.Response.Buffer = True
      HttpContext.Current.Response.Clear()
      HttpContext.Current.Response.ClearHeaders()
      HttpContext.Current.Response.CacheControl = "no-cache"
      HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName)

      HttpContext.Current.Response.ContentType = "application/vnd.xls"
      HttpContext.Current.Response.Charset = ""
 
       
      Me.EnableViewState = False
      'trvVenAddenteeList.Enabled = True
      Dim oStringWriter As New System.IO.StringWriter()
      Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
      dg.RenderControl(oHtmlTextWriter)
 
      HttpContext.Current.Response.Write(oStringWriter.ToString())
      HttpContext.Current.Response.[End]()
      HttpContext.Current.ApplicationInstance.CompleteRequest()
      'HttpContext.Current.Response.End()
 
    Catch HttpEx As HttpException
      lblErrMsg.Visible = True
      lblErrMsg.ForeColor = Drawing.Color.Red
      lblErrMsg.Text = "The following HTTP Exception occured: " + HttpEx.Message.ToString().Trim() + HttpEx.ErrorCode.ToString()
 
    Catch Ex As Exception
      lblErrMsg.Text = "The following Program Exception occured: " + Ex.Message.ToString().Trim()
      lblErrMsg.Visible = True
      lblErrMsg.ForeColor = Drawing.Color.Red
    End Try
 
  End Sub
Robbe Morris replied to Eric Smith on 03-Sep-13 05:05 PM
For starters, you would want to use a .ashx handler instead of an .aspx page to avoid the ASP.NET page life cycle overhead.

The second is that you are writing a string to the browser and not sending a byte array via Response.BinaryWrite.  So, technically you are not writing an Excel spreadsheet back to the browser.  You are writing html that you want interpreted by the browser as Excel.  I do not know if you can force Chrome to open that up with Microsoft Excel.