I'm trying to export my GridView to excel .xlsx
. When it downloads and I try to open the file it gives me this error message:
Excel cannot open the file ______ because the file format or file extension is not valid...
I tried changing the extension to .xls
and it works just fine but .xlsx
does not.
StringWriter sw = new StringWriter();
HtmlTextWriter Hw = new HtmlTextWriter(sw);
FileInfo fi = new FileInfo(Server.MapPath("~/Style.css"));
StringBuilder sb = new StringBuilder();
StreamReader sr = fi.OpenText();
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
sr.Close();
GridView1.RenderControl(Hw);
Response.ClearContent();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("Content-Disposition", "attachment; filename=GridViewData.xlsx");
Response.Write("<html><head><style type='text/css'>" + sb.ToString() + "</style></head><body>" + sw.ToString() + "</body></html>");
Response.Flush();
Response.End();