0

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();
Saeid Amini
  • 1,313
  • 5
  • 16
  • 26
  • It looks like you are trying to serve HTML, not an excel xlsx – zgood Aug 04 '19 at 12:42
  • @zgood it works properly for xls extension, the problem is with the xlsx. – Osama Al-Hasan Aug 04 '19 at 13:04
  • Start using a specialized library for creating Excel files, like [EPPlus](https://github.com/JanKallman/EPPlus). [Example here](https://stackoverflow.com/a/47293207/5836671) and [here](https://stackoverflow.com/a/39513057/5836671). All you are doing now is creating a HTML page with an .xls extension. – VDWWD Aug 04 '19 at 15:43

0 Answers0