Click here to Skip to main content
14,739,371 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi i want to export grid view to Excel 2010 and i tried the below Code it Save Excel but when i want to open excel sheet that i save it gave me the following message
excel cannot open the file because the file format or file extension is not valid 


What I have tried:

private void ExportToExcel()
    {
        string RegionName = "'"+ DDlRegionName.SelectedItem.Text +"'";
        string Excelfilename = RegionName + DateTime.Now;
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AppendHeader("Content-Disposition:", "attachment; filename=" + Excelfilename + ".xlsx");
        Response.Charset = "";
        Response.ContentEncoding = Encoding.Unicode;
        Response.BinaryWrite(Encoding.Unicode.GetPreamble());
        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        GrdComplaint.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }
Posted
Updated 24-Sep-20 9:41am

Your code isn't writing an Excel file. It's writing an HTML table to a file and sending that file back to the client. Excel can normally interpret the HTML table and parse it into an Excel sheet, but that only works if you write an nice plain HTML table.

If you want an actual Excel workbook, you're going to have to use a library to create the file and put data into it, such as the OpenXML SDK, ClosedXML, EPPlus, ...
   
Start by downloading a file from your code that contains a small amount of data.
Then create an Excel sheet that contains the same data and save it as an XLSX file (using Excel 2010)

Then use an editor to compare the two files: The Excel generated one will be unreadable binary data, make sure the one you generate is similar.

XLSX files are Zipped files, which is why they are unreadable.
Now change the extension on both files to .ZIP and open them again: this time you should be able to see a files list like this:
_rels                (a folder)
docProps             (a folder)
xl                   (a folder)
[Content_Types].xl
Again, the two should be the same or at least very similar.
Continue checking until you find a major difference, and you can start wori=king out from there what is wrong about your data.

Sorry, but we can't do any of that for you!
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



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