对应的详细信息:如下图
如图,根据当前的gv标题对应的id,然后生成excel表格
代码如下:
代码
protected void btnToExcel_Click( object sender, EventArgs e) { DGToExcel(); } public void DGToExcel() { GridView gvNew = new GridView(); gvNew.DataSource = GetData(); gvNew.DataBind(); System.Web.UI.Control ctl = gvNew; HttpContext.Current.Response.AppendHeader( " Content-Disposition " , " attachment;filename=Excel.xls " ); HttpContext.Current.Response.Charset = " UTF-8 " ; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; HttpContext.Current.Response.ContentType = " application/ms-excel " ; // ctl.Page.EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); ctl.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.End(); } private DataTable GetData() { DataTable dt = CreateStructure(); for ( int i = 0 ; i < gvMsg.Rows.Count; i ++ ) { CheckBox cb = (gvMsg.Rows[i].FindControl( " chkSelect " )) as CheckBox; if (cb.Checked) { int MsgId = 0 ; try { MsgId = int .Parse((gvMsg.Rows[i].FindControl( " lblId " ) as Label).Text); } catch (Exception) { continue ; } Message msg = MessageManage.GetMessageById(MsgId); DataRow dr = dt.NewRow(); dr[ " 编号 " ] = msg.Id; dr[ " 标题 " ] = msg.Title; dr[ " 内容 " ] = msg.Content; dr[ " 消息从何处发送 " ] = this .GetMsgAddress(msg.MsgType).ToString(); dr[ " 意向产品 " ] = GetProduct(MsgId); dr[ " 代理人/发信人 " ] = msg.AgentManName; dr[ " 代理区域 " ] = msg.AgentArea; dr[ " 代理产品类型 " ] = GetType(msg.AgentType); dr[ " 电话 " ] = msg.Phone; dr[ " 地址 " ] = msg.Address; dr[ " 发送时间 " ] = msg.SendTime; dt.Rows.Add(dr); } } return dt; } private DataTable CreateStructure() { DataTable dt = new DataTable(); dt.Columns.Add( new DataColumn( " 编号 " , typeof ( int ))); dt.Columns.Add( new DataColumn( " 标题 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 内容 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 消息从何处发送 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 意向产品 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 代理人/发信人 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 代理区域 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 代理产品类型 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 电话 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 地址 " , typeof ( string ))); dt.Columns.Add( new DataColumn( " 发送时间 " , typeof (DateTime))); return dt; }
但是我也遇到了一个问题,就是excel生成的超级链接,是以文本的形式显示出来,哪位大侠遇到这样的问题,请指点迷津.