Search code examples
c#asp.netexcelexport-to-excel

Excel file is in a different format specified by the file extension (Excel exported from gridview)


I'm exporting a gridview to an excel file and it opens just fine. Only thing is, this warning always pops up every time the excel file is opened:

The file you are trying to open < > is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

Code I'm using:

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Single_Raw.xls"));
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
           // some code

            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }
    }

Solution

  • That's because Excel knows this isn't an actual Excel file, even though you've named it with an .xls extension. In the past, to avoid this warning, I've used the Microsoft.Office.Interop.Excel reference to build my output file. Then, you'll have a legitimate Excel file when you're done.

    Microsoft.Office.Interop.Excel

    Edit: I've googled around and found this suggestion from Microsoft, but it requires you to hack the registry of the client's computer (probably not feasible).