Cause
- This happens because in the traditional Export to Excel method, the GridView is first converted to an HTML string and then that HTML string is exported to Excel. Thus originally it is not an Excel file hence the Excel Application throws the warning / error “The file you are trying to open is in a different format than specified by the file extension”.
Such an exported Excel file can only be used for display purpose only and you cannot use it for Excel operations that you can generally perform in a valid Excel file.
Reference taken from here
SOLUTION
You should use CLOSEXML to resolve it.
public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)
{
/****** YOUR ORIGINAL CODE *******/
gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
gridExcel.HeaderRow.Font.Bold = false;
gridExcel.HeaderRow.Height = Unit.Pixel(30);
StringWriter sw = new StringWriter();
gridExcel.RenderControl(new HtmlTextWriter(sw));
string renderedGridView = sw.ToString();
//filename will be like xyz.xls
System.IO.File.WriteAllText(@filename, renderedGridView);
/**************** Set it accordingly by below reference ****************************/
XLWorkbook wb = new XLWorkbook();
var ws = wb.Worksheets.Add(sheetName);
ws.Cell(2, 1).InsertTable(data);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
memoryStream.Close();
}
HttpContext.Current.Response.End();
}
Code reference took from HERE