0

我正在将 html 数据导出到 excel。单击导出按钮后,我立即得到一个 excel 文件,但是当我尝试打开该 excel 文件时,会弹出一个警报,提示文件格式与指定的扩展名不同。我怎样才能摆脱这个警报,请帮助我使用以下代码

HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Server.ScriptTimeout = 600
4

1 回答 1

0

编辑:尝试 .csv 格式。这个对我有用。

protected void btnExport_Click(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Clear();

        string filename = "testExportToCSV";
        DataTable table1 = new DataTable("Customers");

        DataRow row1, row2, row3;

        DataColumn colName = new DataColumn("CustomerName", System.Type.GetType("System.String"));
        DataColumn colCity = new DataColumn("City", System.Type.GetType("System.String"));
        table1.Columns.Add(colName);
        table1.Columns.Add(colCity);

        row1 = table1.NewRow();
        row1["CustomerName"] = "aa";
        row1["City"] = "ss";
        table1.Rows.Add(row1);

        row2 = table1.NewRow();
        row2["CustomerName"] = "bb";
        row2["City"] = "sdd";
        table1.Rows.Add(row2);

        row3 = table1.NewRow();
        row3["CustomerName"] = "cc";
        row3["City"] = "dfgfgf";
        table1.Rows.Add(row3);

        //foreach (System.Data.DataColumn column in table1.Columns)
        //{
        for (int i = 0; i < table1.Columns.Count; i++)
        {
            context.Response.Write(table1.Columns[i].ColumnName.ToString().Replace(",", string.Empty) + ",");

        }
        context.Response.Write(Environment.NewLine);

        //}

        foreach (System.Data.DataRow row in table1.Rows)
        {
            for (int i = 0; i < table1.Columns.Count; i++)
            {
                context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
            }

            context.Response.Write(Environment.NewLine);
        }

        context.Response.ContentType = "text/csv";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
        context.Response.End();

    }

编辑1:

我对您的问题进行了研究,但我发现它对您的问题产生security issue了不良影响system's security if we modify it

Key: HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security
Value: (DWORD)"ExtensionHardening" = 
                         [0 = Disable check; 
                          1 = Enable check and prompt; 
                          2 = Enable check, no prompt deny open]

Default setting if value not present is 1 (enable and prompt).

您可以从此链接参考整篇文章:http: //blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx

编辑2: Steps to Modify Registry...

  1. 点击开始菜单
  2. 在搜索程序和文件中键入运行
  3. 然后输入REGEDIT,按 OK
  4. HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security

希望,它会帮助你。!!谢谢。

如果它解决了您的问题,请将其标记为答案,以便其他人也可以参考。

于 2012-10-31T14:33:07.040 回答