Excel文件是由文件扩展名(从gridview导出的Excel)指定的不同格式

我正在将一个gridview导出到一个excel文件,并打开就好了。 唯一的问题是,每当打开excel文件时总会popup这个警告:

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?

我正在使用的代码:

  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(); } } 

这是因为Excel知道这不是一个真正的Excel文件,即使您已经用.xls扩展名来命名它。 在过去,为了避免这个警告,我使用了Microsoft.Office.Interop.Excel引用来构build我的输出文件。 然后,当您完成后,您将拥有一个合法的Excel文件。

的Microsoft.Office.Interop.Excel

编辑:我search了周围,并从微软发现这个build议 ,但它需要你破解客户端的计算机的registry(可能不可行)。