打开导出的Excel文件时如何避免excel文件格式警报?

时间:2012-10-31 14:02:12

标签: asp.net html vb.net excel

我将html数据导出为ex​​cel。我点击导出按钮后立即收到excel文件,但是当我尝试打开excel文件时,会弹出一个警告,说明文件格式与指定的扩展名不同。我怎么能摆脱这个警报,请使用以下代码帮助我,

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

1 个答案:

答案 0 :(得分: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 ,按确定
  4. HKEY_CURRENT_USER \软件\微软\办公室\ 12.0 \ EXCEL \安全
  5. 希望,它会帮助你。 !感谢。

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