4

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();
        }
    }
Pod Mays
  • 2,563
  • 7
  • 31
  • 44
  • there is another question like this... http://stackoverflow.com/questions/940045/how-to-suppress-the-file-corrupt-warning-at-excel-download – 2GDev May 25 '11 at 14:26
  • 1
    Well, it is right. The file is in a different format. This happens even if you save an excel sheet as HTML and then immediately reopen it. I don't think it is something you can avoid. :( – Chris May 25 '11 at 14:39

1 Answers1

2

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).

WEFX
  • 8,298
  • 8
  • 66
  • 102
  • That is certainly an option. I believe it requires office to be installed on your server though which isn't always an option/good idea. There are third party tools which will allow you to generate Excel files too but they probably aren't free (though office isn't free to install on servers either usually). – Chris May 25 '11 at 14:35
  • @chris but what if office is installed on the client's laptop? will this work? because anyway the whole excel uploading process happens between the client's laptop and the server. – Pod Mays May 26 '11 at 02:40