创建Excel文件时出现文件格式错误

时间:2015-03-24 11:58:00

标签: c# export-to-excel

我使用了一些代码在C#中编写excel。我正在将一些数据导出到excel,但在打开此excel文件时会产生错误。任何人都可以帮我摆脱这个。

打开Excel文件时出现

错误对话框:

“.xls的文件格式和扩展名不匹配。文件可能已损坏或不安全。除非您信任其来源,否则无法打开它。”

我的代码如下。

public string attachment = "attachment; filename=Data" + DateTime.Now.ToString("ddMMyyyhhmmss") + ".xls";

public override void VerifyRenderingInServerForm(Control control)
{
     base.VerifyRenderingInServerForm(control);
}
 private void ExportGridView()
    {
        lblExportError.Text = "";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";

        //Fetch database records

        DataTable dtData = GetURLData(Sitename);

        string strHTML = "";
        strHTML = strHTML + "<table border='1' width='100%'>";

        strHTML = strHTML + "<tr>";
        strHTML = strHTML + "<td><b>#</b></td>";
        strHTML = strHTML + "<td><b>Row ID</b></td>";
        strHTML = strHTML + "<td><b>Product Id</b></td>";
        strHTML = strHTML + "<td><b>Variation Id</b></td>";
        strHTML = strHTML + "<td><b>Score</b></td>";
        strHTML = strHTML + "<td><b>Old URL | New URL</b></td>";
        strHTML = strHTML + "</tr>";

        if (dtData.Rows.Count > 0)
        {
            int index = 1;
            foreach (DataRow dr in dtData.Rows)
            {
                strHTML = strHTML + "<tr>";

                strHTML = strHTML + "<td>" + Convert.ToString(index) + "." + "</td>";
                strHTML = strHTML + "<td>" + Convert.ToString(dr["Id"]) + "</td>";
                strHTML = strHTML + "<td>" + Convert.ToString(dr["ProductId"]) + "</td>";
                strHTML = strHTML + "<td>" + Convert.ToString(dr["VariationId"]) + "</td>";
                strHTML = strHTML + "<td>" + Convert.ToString(dr["Score"]) + "</td>";
                strHTML = strHTML + "<td>" + Convert.ToString(dr["URL"]) + " | " + Convert.ToString(dr["NewURL"]) + "</td>";

                strHTML = strHTML + "</tr>";
                index++;
            }
        }
        else
            lblExportError.Text = "Oops! empty dataset.";

        strHTML = strHTML + "</table>";

        Response.Write(strHTML);

        Response.End();
    }

0 个答案:

没有答案