将网格导出为ex​​cel后文件无法打开

我想将网格导出为ex​​cel。 如果网格有100或更less的行,一切工作正常。 但是我的网格有2000多行。 我没有得到任何错误或例外,但文件不会打开后导出和Excel停止工作。 当我打开文件时,我收到一个警告消息,如“filename.xls的文件格式和扩展名”不匹配,文件可能损坏或不安全,除非您信任它的来源,否则不要打开它。想要打开吗?“

我正在使用下面的代码

Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename= {0}", "IAParts.xls")); Response.ContentType = "application/ms-excel"; System.IO.StringWriter sw = new System.IO.StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; BindGrid();//this method binds the data to grid GridView1.RenderControl(htw); Response.Write(sw.ToString()); sw.Flush(); Response.End(); 

亲爱的朋友为您的关于扩展文件的错误我可以说是关于扩展强化,可以通过查看此链接来解决

http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx

或者在txt文件中使用这些行,并保存为.reg,但这些行可以根据您的版本和需要进行更改[我写这些行以供我使用]

[开始]

Windowsregistry编辑器版本5.00

[HKEY_CURRENT_USER \ Software \ Microsoft \ Office \ 15.0 \ Excel \ Security]“ExtensionHardening”= dword:00000000

[结束]

之后,你将永远不会看到关于扩展或错误…和使用Excel文件我提供你这个function,我search和使用在我的项目;)

 public void ExportToExcel(DataTable dt) { if (dt.Rows.Count > 0) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); DataGrid dgGrid = new DataGrid(); dgGrid.DataSource = dt; dgGrid.DataBind(); dgGrid.RenderControl(hw); Response.ContentType = "application/vnd.ms-excel"; // 2003 office excel Response.AppendHeader("Content-Disposition", "filename=OutPut.xls"); string style = @"<style> TABLE { border: 1px solid black; border-collapse: collapse; } TD {mso-number-format:\@; }</style> "; Response.Write(style); Response.Write(tw.ToString()); Response.End(); } }