我正在将 GridView 导出到 Excel 文件,但是当我打开文件时,首先我收到一个错误,即格式类型和扩展名不匹配,当我打开它时,整个页面都被带入 Excel 文件,而不仅仅是网格视图。
我没有使用更新面板。我尝试使用 GridView 内部和外部的按钮并得到相同的结果,所以它似乎可能来自代码隐藏,如下所示:
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView3.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();