为Gridview 添加合计和导出为excel

项目中需要创建一个统计报表,该报表在Gridview的底部显示所有数据的总数。通过在GridView1_RowDataBound事件中计数,实现了在Footer中添加总计行,并隐藏了非总计列。此外,还提供了导出为Excel的功能,但需要注意设置this.EnableViewState = false以确保导出的文件可打开。导出过程包括设置响应内容类型、编码、附件头,以及将GridView内容写入到Response中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目需求做一个统计报表,要求在最后加一个统计以上所有显示数据的条数,代码如下

  1. int i=0;
  2. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  3.         {
  4.            
  5.             if (e.Row.RowType == DataControlRowType.DataRow) //获取数据行,i要定义成全局的
  6.             {
  7.                 i++;
  8.             }
  9.             if (e.Row.RowType == DataControlRowType.Footer) 
  10.             {
  11.                 TableCellCollection tcl = e.Row.Cells; //获取footer表
  12.                 int j = tcl.Count;
  13.                 for (int k = 0; k < j; k++)
  14.                 {
  15.                     if (k != 0 && k != 1)
  16.                     {
  17.                         e.Row.Cells[k].Visible = false;  //禁用除 0,1外所有列
  18.                         
  19.                     }
  20.                 }
  21.                  
  22.                 e.Row.Cells[0].Text = "合计";      //添加合计及合计数据
  23.                 e.Row.Cells[1].Text = i.ToString();
  24.                 e.Row.Cells[1].ColumnSpan = 15;   //需要跨越的列数
  25.             }
  26.         }

导出excel  要记得加this.EnableViewState = false;不然有可能导出的excel打不开,

  1.  this.EnableViewState = false;
  2.                 string style = @"<style> .text { mso-number-format:/@; } </script> ";
  3.                 Response.ClearContent();
  4.                 Response.Charset = "GB2312";
  5.                 Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  6.                 Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
  7.                 Response.AppendHeader("content-disposition""attachment;filename=/"" + System.Web.HttpUtility.UrlEncode("省局PC服务器一览表-最新版本", System.Text.Encoding.UTF8) + ".xls/"");
  8.                 StringWriter sw = new StringWriter();
  9.                 HtmlTextWriter htw = new HtmlTextWriter(sw);
  10.                 GridView1.RenderControl(htw);
  11.                 // Style is added dynamically
  12.                 Response.Write(style);
  13.                 Response.Write(sw.ToString());
  14.                 Response.End();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值