C#实现GridView导出Excel实例代码
作者:rush_me 发布时间:2023-10-29 04:31:09
标签: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();
}
}
}
来源:http://www.cnblogs.com/rushme/p/6613987.html?utm_source=tuicool&utm_medium=referral


猜你喜欢
- 如下所示:Synchronized是内置的java关键字,Lock是一个java类。Synchronized无法判断是否获取到了锁,Lock
- 在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,List
- 最近做MVC网站时刚好用到,用以提供一个完整的文件夹并压缩下载,正好做个笔记。拷贝文件夹的所有内容到另一个文件夹内:public stati
- JAVA枚举,比你想象中还要有用!我经常发现自己在Java中使用枚举来表示某个对象的一组潜在值。在编译时确定类型可以具有什么值的能力是一种强
- 此方案适用于解决springboot项目运行时动态添加数据源,非静态切换多数据源!!!一、多数据源应用场景:1.配置文件配置多数据源,如默认
- 首先从字面意思理解两个词onTouchEvent:触发触摸事件onInterceptTouchEvent:触发拦截触摸事件通过查看源代码及类
- Spring是什么?Spring是一个轻量级Java开发框架,最早有Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其
- 大家使用Android的原生UI都知道,Android的Activity跳转就是很生硬的切换界面。其实Android的Activity跳转可
- 本文实例为大家分享了Flutter实现底部导航栏的具体代码,供大家参考,具体内容如下效果实现先将自动生成的main.dart里面的代码删除,
- 刚开始我以为熔断和降级是一体的,以为他们必须配合使用; 只不过名字不一样而已,但是当我经过思考过后,发现他们其实不是一个东西;降级什么是服务
- IDEA设置Tab选项卡本人喜欢把tab选项卡全部放出来(tab选项卡默认是10个,超过后会把最先打开的挤出去,像队列一样先进先出),比如这
- 微服务feign调用添加token1.一般情况是这么配置的具体的怎么调用就不说了 如下配置,就可以在请求头中添加需要的请求头信息。packa
- 本文为大家分享了Unity实现粒子光效导出成png序列帧的具体代码,供大家参考,具体内容如下这个功能并不是很实用,不过美术同学有这样的需求,
- 日常工作中,不管你是写Unit Test,还是采用TDD的编程方式进行开发,都会遇到断言。而断言的风格常见的会有Assert、BDD风格,对
- 一、MyBatis的逆向⼯程(1)所谓的逆向⼯程是:根据数据库表逆向⽣成Java的pojo类,SqlMapper.xml⽂件,以及Mappe
- 上一篇文章已经介绍了如何为RecyclerView添加FootView,在此基础上,要添加分页加载的功能其实已经很简单了。 上一篇文章地址:
- 在电商上购买商品后,如果在下单而又没有支付的情况下,一般提示30分钟完成支付,否则订单自动。比如在京东下单为完成支付:超过24小时,就会自动
- 问题怎么配置springBoot 内置tomcat,才能使得自己的服务效率更高呢?基础配置Spring Boot 能支持的最大并发量主要看其
- 前言:由于项目需求,短信验证码的接口需要换成阿里大于的,但是尴尬的发现阿里大于的jar包没有maven版本的,于是便开始了一上午的 * 引包之
- JPA like 模糊查询 语法格式public List<InstitutionInfo> getAllInstitution