我将html数据导出为excel。我点击导出按钮后立即收到excel文件,但是当我尝试打开excel文件时,会弹出一个警告,说明文件格式与指定的扩展名不同。我怎么能摆脱这个警报,请使用以下代码帮助我,
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Server.ScriptTimeout = 600
答案 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...
希望,它会帮助你。 !感谢。
如果它解决了您的问题,请将其标记为答案,以便其他人也可以参考。