简体   繁体   English

c#export to excel file getting error message

[英]c# export to excel file getting error message

I am using Excel 2010 I have the following code that I like to export to a xls file but I am getting the following message: 我正在使用Excel 2010我有以下代码,我想导出到xls文件,但我收到以下消息:

The file you are trying to open, 'Report.xls', is in a different format than specified by the file extension. 您尝试打开的文件“Report.xls”的格式与文件扩展名指定的格式不同。 Verify that the file is not corrupted and is for the trusted source before opening the file. 在打开文件之前,请验证文件是否已损坏并且是否为受信任的源。 Do you want to open the file now? 你想现在打开文件吗?

Note that is still opens but not sure why I am getting the message 请注意,仍然打开但不确定我收到消息的原因

           ....
            a.Fill(dtRecords);

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
            Response.ContentType = "application/ms-excel";
            string tab = string.Empty;

            foreach (DataColumn datacol in dtRecords.Columns)
            {
                Response.Write(tab + datacol.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");

            foreach (DataRow dr in dtRecords.Rows)
            {
                tab = "";
                for (int j = 0; j < dtRecords.Columns.Count; j++)
                {
                    Response.Write(tab + Convert.ToString(dr[j]));
                    tab = "\t";
                }

                Response.Write("\n");
            }
            Response.End();

我相信.xls文件的官方mime类型是application/vnd.ms-excelsource

You are getting this message because you are trying to export character separated value (CSV) stream as XLS file. 您收到此消息是因为您尝试将字符分隔值(CSV)流导出为XLS文件。

CSV is textual format, while XLS is complex binary format with much more features than CSV. CSV是文本格式,而XLS是复杂的二进制格式,具有比CSV更多的功能。

MS Excel complains because it first tried to open the file as XLS but it figured out that file is actually not XLS so it shows warning message, but is still smart enough to figure out that file is CSV and act accordingly. MS Excel抱怨,因为它首先尝试将文件作为XLS打开,但它发现该文件实际上不是XLS,因此它显示警告消息,但仍然足够聪明,可以确定该文件是CSV并采取相应的行动。

Try saving the file with extension .csv and with content-type text/csv . 尝试使用扩展名.csv和内容类型text/csv保存文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM