您的位置:首页 > 其它

为Gridview 添加合计和导出为excel

2008-12-03 04:28 453 查看
项目需求做一个统计报表,要求在最后加一个统计以上所有显示数据的条数,代码如下

int i=0;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow) //获取数据行,i要定义成全局的

{

i++;

}

if (e.Row.RowType == DataControlRowType.Footer)

{

TableCellCollection tcl = e.Row.Cells; //获取footer表

int j = tcl.Count;

for (int k = 0; k < j; k++)

{

if (k != 0 && k != 1)

{

e.Row.Cells[k].Visible = false; //禁用除 0,1外所有列

}

}

e.Row.Cells[0].Text = "合计"; //添加合计及合计数据

e.Row.Cells[1].Text = i.ToString();

e.Row.Cells[1].ColumnSpan = 15; //需要跨越的列数

}

}

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

this.EnableViewState = false;

string style = @"<style> .text { mso-number-format:/@; } </script> ";

Response.ClearContent();

Response.Charset = "GB2312";

Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");

Response.AppendHeader("content-disposition", "attachment;filename=/"" + System.Web.HttpUtility.UrlEncode("省局PC服务器一览表-最新版本", System.Text.Encoding.UTF8) + ".xls/"");

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.RenderControl(htw);

// Style is added dynamically

Response.Write(style);

Response.Write(sw.ToString());

Response.End();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: