0

I want to do an onclick function that downloads an excel file that is also created when a user clicks a button, so I found this function that I am using for the onclick

        public void CreateExcel(object sender, EventArgs e) 
    {
        DataTable dt;
        dt = Database.Get_All_Approval_Table_Grouped            
        string attachment = "attachment; filename=example.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/vnd.ms-excel";
        string tab = "";
        foreach (DataColumn dc in dt.Columns)
        {
            Response.Write(tab + dc.ColumnName);
            tab = "\t";
        }
        Response.Write("\n");
        int i;
        foreach (DataRow dr in dt.Rows)
        {
            tab = "";
            for (i = 0; i < dt.Columns.Count; i++)
            {
                Response.Write(tab + dr[i].ToString());
                tab = "\t";
            }
            Response.Write("\n");
        }
        Response.End();
    }

The following is the response I receive:

Line: 885
Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.
Kevin
  • 1,574
  • 4
  • 19
  • 45
  • Also, is that the correct content type? It's not an Excel file - it's tab-delimited text. – John Saunders Jun 15 '15 at 18:31
  • what is the file ext of the excel is it .csv or xls `Response.ContentType = "application/vnd.ms-excel";` should work if not try the following `Response.ContentType = "application/vnd.xls";` also why not put your `AddHeader` section something like the following `Response.AddHeader("content-disposition", "attachment;filename=e1.xls");` – MethodMan Jun 15 '15 at 18:31

1 Answers1

0

The error is because you not not downloading an Excel file, you're serving an ASP.net WebForms page.

You are modifying the response out from under WebForms.

Also, that's not Excel

Even if you solved the problem (by using an .ashx handler to serve raw content), Excel will then reject it.

Your server is indicating that the Content-Type is application/vnd.ms-excel:

Response.ContentType = "application/vnd.ms-excel";

Except that it isn't an Excel file. When Excel tries to unzip the .xlsx file, it will fail with a security warning that the content does not match the indicated type.

Community
  • 1
  • 1
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219