Search code examples
asp.netexcelexport-to-excel

Where has the GUI gone?


I have a simple ASPX page that renders a dynamically generated HTML table to Excel. It works, but as you can see from the screenshot, for some reason opening the workbook results in the Excel instance having no GUI to speak of aside from the Formula bar and the worksheet tabs at the bottom. It can't be easily closed or quit either and seems to slow my workstation down too.

I'm using this code to build and export the table.

        runReport2();//Builds the table - this bit is fine.

        Response.Clear();
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-disposition", "attachment;filemename=" + "FleetReport.xls");

        System.IO.StringWriter sw = new System.IO.StringWriter(); 
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        this.tblReport.RenderControl(hw);
        System.Text.StringBuilder sb1 = new System.Text.StringBuilder();

        sb1.Append(sw.ToString() );
        sw = null;
        hw = null;
        Response.Write(sb1.ToString());
        sb1.Remove(0, sb1.Length);
        Response.Flush();
        Response.End();

Can you suggest what I might be doing wrong? Am I doing this in a sensible way or should I be sending CSV to Excel instead?


Solution

  • Try this way

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; Filename = FleetReport.xls"));
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            this.tblReport.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();