Dears,
I want to download a DataTable Data as Excel 2013 File Not excel 2003.
Here is my code:
private void DownloadExcelReport(DataTable dtResult)
{
var gv = new GridView
{
DataSource = dtResult
};
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=AllDataReport.xlsx");
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
gv.RenderControl(objHtmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.End();
}
The Result:
The file is downloaded as .xlsx File but i CANNOT OPEN IT.
This Message Appears:
Excel cannot open the file because the extension is not valid verify that the file is not corrupted and that the file extension matches the format of the file.
What I have tried:
I did some search and i found the following:
Change the content type and response header from this:
//Response.AddHeader("content-disposition", "attachment; filename=AllDataReport.xls");
//Response.ContentType = "application/ms-excel";
To Be Like This:
Response.AddHeader("content-disposition", "attachment; filename=AllDataReport.xlsx");
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";