Im always getting error when i open my file "the file extension is invalid"
HttpResponse r = Response;
//clean up the response.object
r.Clear();
r.Buffer = true;
r.Charset = "UTF-8";
//set the response mime type for excel
r.ContentType = "application/vnd.ms-excel";
string attachment = "attachment; filename=Report" + ".xls";
r.AddHeader("content-disposition", attachment);
r.ContentEncoding = new System.Text.UTF8Encoding();
r.Write(content);
r.End();
Anyone whats the problem ?
Loading

Sanjeeb LenkaRank #301 · 8.3K reputationPosted Jun 21, 2013, 10:07 AM EDT
HttpResponse r = Response;
//clean up the response.object
r.Clear();
r.Buffer = true;
r.Charset = "UTF-8";
//set the response mime type for excel
r.ContentType = "application/vnd.ms-excel";
string attachment = "attachment; filename=Report" + ".xls";
r.AddHeader("content-disposition", attachment);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
gvdetails.RenderControl(htw);
r.Write(sw.ToString());
r.End();
gvdetails is the grid you want to export.
or you can follow this link
http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html
if any problem reply
Nishanthan Ganeshan16 reputationPosted Jun 21, 2013, 10:50 AM EDT
Nishanth
Sanjeeb LenkaRank #301 · 8.3K reputationPosted Jun 21, 2013, 7:11 PM EDT
Which office version you are using if you are using older version like 2003 then it will open and in newer version it will show warning.
so if you want to convert it to xlsx below below link.
http://aakarsoft.com/wordpress/index.php/export-gridview-data-to-excel-xlsx-without-using-htmltextwriter-in-asp-net/
in your code :
use this two name space for above link code:
using OfficeOpenXml;
using OfficeOpenXml.Style;
if any problem reply
Neboja12 reputationPosted Jul 16, 2014, 1:54 AM EDT
Hi, you are right, the file is in html format. If you want to create a real XLS file with binary content (BIFF8) then you will need to do a conversion from HTML formatted content to an XLS formatted content with C#, for example like the following:
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw); gvdetails.AllowPaging = false; gvdetails.DataBind(); gvdetails.RenderControl(htw); ExcelFile excel; var option = LoadOptions.HtmlDefault; using (var htmlStream = new MemoryStream(option.Encoding.GetBytes(sw.ToString()))) excel = ExcelFile.Load(htmlStream, option); excel.Save(Response, "Report.xls");Note that with this you do not have to explicitly set anything on current Response, it will stream the file to the client's browser with a Save method call.
Also this code uses a .NET library for excel transformations, you can achieve various requirements by processing your XLS file in C# with it.