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

时间:2021-12-03 08:24:31

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:

我正在将gridview导出到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?

您尝试打开的文件<>的格式与文件扩展名指定的格式不同。在打开文件之前,请验证文件是否已损坏且来自受信任的源。你想现在打开文件吗?

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

1 个解决方案

#1


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.

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

Microsoft.Office.Interop.Excel

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

编辑:我已经google了一遍,并发现了微软的这个建议,但它要求你破解客户端计算机的注册表(可能不可行)。

#1


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.

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

Microsoft.Office.Interop.Excel

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

编辑:我已经google了一遍,并发现了微软的这个建议,但它要求你破解客户端计算机的注册表(可能不可行)。