龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

C#实现把GridView或DataSet数据导出到Excel文件

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
下面代码实现GridView或DataSet数据导出到Excel文件,已解决分页这些问题 public override void VerifyRenderingInServerForm(Control control) { //base.VerifyRenderingInServerForm(control); } private void Export(GridView gvU

下面代码实现GridView或DataSet数据导出到Excel文件,已解决分页这些问题
public override void VerifyRenderingInServerForm(Control control)
{
 //base.VerifyRenderingInServerForm(control);
}

private void Export(GridView gvUser, string Style, string FileType, string FileName)
{
 Response.ClearContent();
 Response.Charset = "GB2312";
 Response.ContentEncoding = System.Text.Encoding.UTF8;
 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
 Response.ContentType = FileType;
 //page.Response.ContentType = "application/ms-excel";
 Page.EnableViewState = false;
 StringWriter sw = new StringWriter();
 HtmlTextWriter hw = new HtmlTextWriter(sw);
 //turn off paging
 gvUser.AllowPaging = false;
 BindGrid(gvUser);

 gvUser.RenderControl(hw);
 Response.Write(Style);
 Response.Write(sw.ToString());
 //page.Response.Flush();
 Response.End();

 //turn the paging on again
 gvUser.AllowPaging = true;
 BindGrid(gvUser);
}
private void BindGrid(GridView gvUser)
{
 DataSet ds = new DataSet();
 ds = Session["myDataSet"] as DataSet;
 gvUser.DataSource = ds;
 gvUser.DataBind();
}

protected void gvMessageByGroup_RowDataBound(object sender, GridViewRowEventArgs e)
{
 e.Row.Attributes.Add("onmouseover", "currentcolor = this.style.backgroundColor;this.style.backgroundColor = '#cee5f8'");
 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor =currentcolor;");
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  e.Row.Cells[3].Attributes["class"] = "text";
 }
}

protected void lbtnExportToExcel_Click(object sender, EventArgs e)
{
 string strStyle = @"<style> .text { mso-number-format:\@; }</style>";
 Export(gvMessageByGroup, strStyle, "application/ms-excel", "myExcel.xls");
}

精彩图集

赞助商链接