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

本文关键字:Excel 格式 文件 gridview 导出 扩展名 | 更新日期: 2023-09-27 17:57:43

我正在将网格视图导出到excel文件中,它打开得很好。唯一的问题是,每次打开excel文件时都会弹出此警告:

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从gridview导出)

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

Microsoft.Office.Interop.Excel

编辑:我在谷歌上搜索了一下,发现了微软的这个建议,但它需要你破解客户端计算机的注册表(可能不可行)。