C#实现GridView导出Excel实例代码
导出Excel在很多项目中经常用到,本人介绍了C#实现GridView导出Excel实例代码,也全当给自己留下个学习笔记了。
usingSystem.Data; usingSystem.Web; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; usingSystem.IO; usingSystem.Text; namespaceDotNet.Utilities { //////SummarydescriptionforGridViewExport /// publicclassGridViewExport { publicGridViewExport() { // //TODO:Addconstructorlogichere // } publicstaticvoidExport(stringfileName,GridViewgv) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader( "content-disposition",string.Format("attachment;filename={0}",fileName)); HttpContext.Current.Response.ContentType="application/ms-excel"; //HttpContext.Current.Response.Charset="utf-8"; using(StringWritersw=newStringWriter()) { using(HtmlTextWriterhtw=newHtmlTextWriter(sw)) { //Createaformtocontainthegrid Tabletable=newTable(); table.GridLines=GridLines.Both;//单元格之间添加实线 //addtheheaderrowtothetable if(gv.HeaderRow!=null) { PrepareControlForExport(gv.HeaderRow); table.Rows.Add(gv.HeaderRow); } //addeachofthedatarowstothetable foreach(GridViewRowrowingv.Rows) { PrepareControlForExport(row); table.Rows.Add(row); } //addthefooterrowtothetable if(gv.FooterRow!=null) { PrepareControlForExport(gv.FooterRow); table.Rows.Add(gv.FooterRow); } //renderthetableintothehtmlwriter table.RenderControl(htw); //renderthehtmlwriterintotheresponse HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } //////Replaceanyofthecontainedcontrolswithliterals /// ///privatestaticvoidPrepareControlForExport(Controlcontrol) { for(inti=0;i ///导出Grid的数据(全部)到Excel ///字段全部为BoundField类型时可用 ///要是字段为TemplateField模板型时就取不到数据 /// /// grid的ID /// 数据源 /// 要导出Excel的文件名 publicstaticvoidOutputExcel(GridViewgrid,DataTabledt,stringexcelFileName) { Pagepage=(Page)HttpContext.Current.Handler; page.Response.Clear(); stringfileName=System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName)); page.Response.AddHeader("Content-Disposition","attachment:filename="+fileName+".xls"); page.Response.ContentType="application/vnd.ms-excel"; page.Response.Charset="utf-8"; StringBuilders=newStringBuilder(); s.Append(" "+fileName+" "); intcount=grid.Columns.Count; s.Append(" "); s.AppendLine(" "); for(inti=0;i "); foreach(DataRowdrindt.Rows) { s.AppendLine(""+grid.Columns[i].HeaderText+""); //s.Append(" "+grid.Columns[i].HeaderText+" "); } s.Append(""); for(intn=0;n "); } s.Append(""); s.Append(""); page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString())); page.Response.End(); } } }"+dr[((BoundField)grid.Columns[n]).DataField].ToString()+""); } s.AppendLine("
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。