日期:2014-05-17 浏览次数:20502 次
public partial class GridViewToExcel : System.Web.UI.Page { GridView gridToExport = null; protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 必须override这个方法,否则会报错 /// /// "Control 'ctl00_MainContent_Gridview1' of type 'GridView' must be placed /// inside a form tag with runat=server", /// even though you have the supposedly missing form tag. /// /// </summary> /// <param name="control"></param> public override void VerifyRenderingInServerForm(Control control) { //base.VerifyRenderingInServerForm(control); } protected void btnExport_Click(object sender, EventArgs e) { gridToExport = gvwEmployee; } protected override void Render(HtmlTextWriter writer) { if (gridToExport as GridView != null) { ExportGridToExcel(gridToExport, "test.xls"); } base.Render(writer); } private void ExportGridToExcel(GridView grid, string filename) { // 检查是否有文件名 if (string.IsNullOrEmpty(filename)) { throw new ArgumentException("Export filename is required"); } // 检查是否是excel格式 if (!filename.EndsWith(".xls")) { filename += ".xls"; } grid.AllowPaging = false; // 禁止分页 grid.AllowSorting = false; // 禁止排序 grid.DataBind(); // 绑定数据 StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment;filename=" + filename); Response.Charset = string.Empty; Page.EnableViewState = false; grid.RenderControl(hw); Respo