asp.net 方法:Gridview 2 Execl Exportar
--------------------方法1-----------------------------------------------
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Page page = new Page();
HtmlForm form = new HtmlForm();
GridView1.EnableViewState = false;
// Deshabilitar la validación de eventos, sólo asp.net 2
page.EnableEventValidation = false;
// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(GridView1);
page.RenderControl(htw);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();
-----------------------------------方法2----------------------------------------------------------
GridView gvExcel = new GridView();
gvExcel.RowDataBound += new GridViewRowEventHandler(gvExcel_RowDataBound);
Response.Buffer = true;
Response.ClearContent();
//Response.ClearHeaders();
//指定http名称和值
Response.AddHeader("content-disposition", "attachment; FileFormat=xlNormal;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
//指定文件类型
Response.ContentType = "application/excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
StringWriter sw = new StringWriter();
gvExcel.AllowPaging = false;
gvExcel.DataSource = dt;
gvExcel.DataBind();
//HtmlTextWriter 输出流
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvExcel.RenderControl(htw);
string style = @"<style> .text { mso-number-format:\@; } </script> "; //单元格式为文本格式
//sw写入到http输出流
Response.Output.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
gvExcel.Visible = false;