C#实现GridView导出Excel实例代码
作者:rush_me 时间:2023-10-29 04:31:09
导出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
标签:C#,gridview,excel
0
投稿
猜你喜欢
Android EditText每4位自动添加空格效果
2022-04-30 20:08:17
C# Winform 子窗体访问父级窗体的控件和属性
2022-08-15 04:37:06
Java数据结构之单链表详解
2023-11-04 17:02:20
Android项目实战之百度地图地点签到功能
2022-09-04 09:30:47
Java基于TCP方式的二进制文件传输
2023-06-04 18:23:52
JAVA遍历map的几种实现方法代码
2023-08-27 22:06:04
Maven将代码及依赖打成一个Jar包的方式详解(最新推荐)
2022-03-31 06:52:47
利用C#实现SSLSocket加密通讯的方法详解
2023-03-01 02:23:05
Spring Cloud Hystrix异常处理方法详解
2022-05-29 06:20:12
Android Flutter实现五种酷炫文字动画效果详解
2023-06-27 02:57:16
SpringBoot 实现自定义的 @ConditionalOnXXX 注解示例详解
2023-04-04 03:37:18
android studio 4.0 新建类没有修饰符的方法
2023-02-06 04:56:52
Java中对象与C++中对象的放置安排的对比
2022-05-31 15:07:18
C#怎样才能将XML文件导入SQL Server
2022-02-16 17:51:13
android 实现类似微信缓存和即时更新好友头像示例
2023-12-04 20:47:41
Unity实现苹果手机Taptic震动
2023-02-15 07:18:47
SpringBoot用@Async注解实现异步任务
2023-08-07 06:36:09
ssm框架下web项目,web.xml配置文件的作用(详解)
2021-07-31 14:42:11
maven中配置项目的jdk版本无效的排查方式
2023-07-18 21:43:42
springboot 如何解决static调用service为null
2022-09-05 05:30:03