protected void btnExportExcel_Click(object sender, EventArgs e) { GridView gvclaimxuat = new GridView(); DataTable dt = new DataTable(); string id = cldao.LayMaTheoTen(lblThamChieuHead.Text); dt = cldao.XuatClaim(id); int dem = dt.Rows.Count; gvclaimxuat.DataSource = dt; gvclaimxuat.DataBind(); //Export(dt, "Claim", lblThamChieuHead.Text); ExportToExcel(lblThamChieuHead.Text + ".xls", gvclaimxuat); gvclaimxuat = null; gvclaimxuat.Dispose(); }
/// <summary> /// 邦定GridView /// </summary> /// <param name="DataScore">数据源</param> /// <param name="GV">GridView控件</param> public virtual void BindDataList(object DataScore, System.Web.UI.WebControls.GridView GV) { GV.DataSource = DataScore; GV.DataBind(); GV.Dispose(); }
/// <summary> /// 导出GridView中的数据到Excel /// </summary> /// <param name="gvw"></param> /// <param name="title"></param> /// <param name="TableName"></param> private static void ExportToExcel(GridView gvw, string title, string TableName) { //int coun = ExistsRegedit(); //string fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now); //if (coun >0) //{ // fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now); // //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7; //} //else //{ // HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; // //Page.RegisterStartupScript("mess", "<script>alert('该机器没有安装任何office软件');</script>"); // //return; //} for (var i = 0; i < gvw.Rows.Count; i++) { for (var j = 0; j < gvw.HeaderRow.Cells.Count; j++) { //这里给指定的列编辑格式,将数字输出为文本,防止数字溢出 gvw.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); //nowrap="nowrap" 不换行 gvw.Rows[i].Cells[j].Attributes.Add("nowrap", "nowrap"); } } HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); //fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now); HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(TableName) + HttpUtility.UrlEncode(title) + ".xls"); HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; var tw = new StringWriter(); var hw = new HtmlTextWriter(tw); gvw.RenderControl(hw); if (!string.IsNullOrEmpty(title)) { HttpContext.Current.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" + title + "</font></center></b>"); } HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.Close(); HttpContext.Current.Response.End(); gvw.Dispose(); tw.Dispose(); hw.Dispose(); }