Click here to Skip to main content
15,909,953 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dears,

I want to download a DataTable Data as Excel 2013 File Not excel 2003.
Here is my code:

C#
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";
Posted
Updated 7-Jul-18 1:29am
Comments
Patrice T 7-Jul-18 4:22am    
Simply naming a file xlsx is not enough to make it an excel file.
What is the content of the file ?
_ProgProg_ 7-Jul-18 4:25am    
Rows and columns. Arabic data
Patrice T 7-Jul-18 4:48am    
What is the file format
_ProgProg_ 7-Jul-18 4:58am    
I simply have data from data base not exported to any file format.
I want to export it to .xlsx format.
Patrice T 7-Jul-18 5:02am    
you need to use a library to export in xlsx file format or export in a standard text file format like csv

1 solution

If you have a datatable, you can save it as a xml file using the DataTable.WriteXML() method, and then open that file in excel.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900