C#实现GridView导出Excel实例代码
导出Excel在很多项目中经常用到,本人介绍了C#实现GridView导出Excel实例代码,也全当给自己留下个学习笔记了。
using System.Data; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Text; namespace DotNet.Utilities { /// <summary> /// Summary description for GridViewExport /// </summary> public class GridViewExport { public GridViewExport() { // // TODO: Add constructor logic here // } public static void Export(string fileName, GridView gv) { 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 (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // Create a form to contain the grid Table table = new Table(); table.GridLines = GridLines.Both; //单元格之间添加实线 // add the header row to the table if (gv.HeaderRow != null) { PrepareControlForExport(gv.HeaderRow); table.Rows.Add(gv.HeaderRow); } // add each of the data rows to the table foreach (GridViewRow row in gv.Rows) { PrepareControlForExport(row); table.Rows.Add(row); } // add the footer row to the table if (gv.FooterRow != null) { PrepareControlForExport(gv.FooterRow); table.Rows.Add(gv.FooterRow); } // render the table into the htmlwriter table.RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } /// <summary> /// Replace any of the contained controls with literals /// </summary> /// <param name="control"></param> private static void PrepareControlForExport(Control control) { for (int i = 0; i < control.Controls.Count; i++) { Control current = control.Controls[i]; if (current is LinkButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); } else if (current is ImageButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); } else if (current is HyperLink) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); } else if (current is DropDownList) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); } else if (current is CheckBox) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); } if (current.HasControls()) { PrepareControlForExport(current); } } } /// <summary> /// 导出Grid的数据(全部)到Excel /// 字段全部为BoundField类型时可用 /// 要是字段为TemplateField模板型时就取不到数据 /// </summary> /// <param name="grid">grid的ID</param> /// <param name="dt">数据源</param> /// <param name="excelFileName">要导出Excel的文件名</param> public static void OutputExcel(GridView grid, DataTable dt, string excelFileName) { Page page = (Page)HttpContext.Current.Handler; page.Response.Clear(); string fileName = 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"; StringBuilder s = new StringBuilder(); s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>"); int count = grid.Columns.Count; s.Append("<table border=1>"); s.AppendLine("<tr>"); for (int i = 0; i < count; i++) { if (grid.Columns[i].GetType() == typeof(BoundField)) s.Append("<td>" + grid.Columns[i].HeaderText + "</td>"); //s.Append("<td>" + grid.Columns[i].HeaderText + "</td>"); } s.Append("</tr>"); foreach (DataRow dr in dt.Rows) { s.AppendLine("<tr>"); for (int n = 0; n < count; n++) { if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField)) s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>"); } s.AppendLine("</tr>"); } s.Append("</table>"); s.Append("</body></html>"); page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString())); page.Response.End(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
上一篇:C#中抽象类与接口的区别详解
栏 目:C#教程
下一篇:c#读取XML多级子节点
本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/5813.html
您可能感兴趣的文章
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新闻效果的方法
- 01-10C#实现清空回收站的方法
- 01-10C#实现读取注册表监控当前操作系统已安装软件变化的方法
- 01-10C#实现多线程下载文件的方法
- 01-10C#实现Winform中打开网页页面的方法
- 01-10C#实现远程关闭计算机或重启计算机的方法
- 01-10C#自定义签名章实现方法
- 01-10C#文件断点续传实现方法
- 01-10winform实现创建最前端窗体的方法
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 04-02jquery与jsp,用jquery
- 01-10C#中split用法实例总结
- 01-10delphi制作wav文件的方法
- 01-11ajax实现页面的局部加载
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-10SublimeText编译C开发环境设置
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 08-05织梦dedecms什么时候用栏目交叉功能?