GridView数据导出到excel

GridView1.AllowPaging = false;//设置GridView控件不能分页

GridView1.AllowSorting = false;//设置GridView控件不能排序 

mybind();

ToExcel(GridView1, "CZBack.xls");

GridView1.AllowPaging = true;//恢复GridView控件分页

GridView1.AllowSorting = true;//恢复GridView控件排序

mybind();//数据绑定函数

//excel导出函数

private void ToExcel(Control ctl, string FileName)

{

HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

HttpContext.Current.Response.Charset = "utf-8";

HttpContext.Current.Response.ContentType = "application/ms-excel";

HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);

ctl.Page.EnableViewState = false;

System.IO.StringWriter tw = new System.IO.StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(tw);

ctl.RenderControl(hw);

HttpContext.Current.Response.Write(tw.ToString());

HttpContext.Current.Response.End();

}

public override void VerifyRenderingInServerForm(Control control)

{

// Confirms that an HtmlForm control is rendered for

}

处理字符串

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

e.Row.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

}

posted @ 2011-11-15 15:30  neway  阅读(208)  评论(0)    收藏  举报