在 asp.net c# 中将数据表转换为 excel 后的错误消息

error message after converting datatable to excel in asp.net c#

在 asp.net c#

中将数据表转换为 excel 后出现错误消息

下面是我正在使用的代码

 Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
    Response.ContentType = "application/ms-excel";
    DataTable dt = ds.Tables[0];
    string str = string.Empty;
    foreach (DataColumn dtcol in dt.Columns)
    {
        Response.Write(str + dtcol.ColumnName);
        str = "\t";
    }
    Response.Write("\n");
    foreach (DataRow dr in dt.Rows)
    {
        str = "";
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            Response.Write(str + Convert.ToString(dr[j]));
            str = "\t";
        }
        Response.Write("\n");
    }
    Response.End();

错误信息是

  ![Your trying to open different format or corrupted file ][2] 

点击确定后打开,但我不想显示此消息.... 我哪里出错了... 谢谢...

您的内容类型有误。您正在创建 CSV 输出,而不是 Excel。将内容类型更改为 text/csv 并将文件扩展名更改为 .csv.

How to use the CSV MIME-type?

Link 到 OpenXML SDK,让您创建任何 Office 格式:http://msdn.microsoft.com/en-us/library/office/bb448854%28v=office.15%29.aspx