导出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#
# gridview导出excel
# gridview导出到excel
# 导出excel
# C#导出GridView数据到Excel文件类实例
# C#使用RenderControl将GridView控件导出到EXCEL的方法
# c#利用Excel直接读取数据到DataGridView
# 给自己
# 时就
# 大家多多
# 单元格
# 学习笔记
# sw
# grid
# utf
# StringWriter
# form
# Create
# HtmlTextWriter
# htw
# Charset
# Format
# attachment
# content
# disposition
# filename
# ms
相关文章:
黑客入侵网站服务器的常见手法有哪些?
如何在宝塔面板中修改默认建站目录?
,制作一个手机app网站要多少钱?
建站之星如何实现网站加密操作?
如何制作网站标识牌,动态网站如何制作(教程)?
如何选择建站程序?包含哪些必备功能与类型?
招商网站制作流程,网站招商广告语?
如何高效完成自助建站业务培训?
金*站制作公司有哪些,金华教育集团官网?
交易网站制作流程,我想开通一个网站,注册一个交易网址,需要那些手续?
盐城做公司网站,江苏电子版退休证办理流程?
如何通过网站建站时间优化SEO与用户体验?
定制建站策划方案_专业建站与网站建设方案一站式指南
mc皮肤壁纸制作器,苹果平板怎么设置自己想要的壁纸我的世界?
北京制作网站的公司排名,北京三快科技有限公司是做什么?北京三快科技?
香港服务器建站指南:免备案优势与SEO优化技巧全解析
JS中使用new Date(str)创建时间对象不兼容firefox和ie的解决方法(两种)
企业网站制作公司网页,推荐几家专业的天津网站制作公司?
网站网页制作电话怎么打,怎样安装和使用钉钉软件免费打电话?
如何快速生成高效建站系统源代码?
网站制作软件免费下载安装,有哪些免费下载的软件网站?
常州自助建站:操作简便模板丰富,企业个人快速搭建网站
制作网站的软件免费下载,免费制作app哪个平台好?
免费制作小说封面的网站有哪些,怎么接网站批量的封面单?
如何确保FTP站点访问权限与数据传输安全?
东莞市网站制作公司有哪些,东莞找工作用什么网站好?
建站之星备案流程有哪些注意事项?
详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)
一键制作网站软件下载安装,一键自动采集网页文档制作步骤?
香港服务器网站卡顿?如何解决网络延迟与负载问题?
网站设计制作公司地址,网站建设比较好的公司都有哪些?
香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化
如何通过cPanel快速搭建网站?
黑客如何利用漏洞与弱口令入侵网站服务器?
小捣蛋自助建站系统:数据分析与安全设置双核驱动网站优化
如何用y主机助手快速搭建网站?
独立制作一个网站多少钱,建立网站需要花多少钱?
如何通过服务器快速搭建网站?完整步骤解析
较简单的网站制作软件有哪些,手机版网页制作用什么软件?
香港代理服务器配置指南:高匿IP选择、跨境加速与SEO优化技巧
道歉网站制作流程,世纪佳缘致歉小吴事件,相亲网站身份信息伪造该如何稽查?
英语简历制作免费网站推荐,如何将简历翻译成英文?
网站企业制作流程,用什么语言做企业网站比较好?
建站ABC备案流程中有哪些关键注意事项?
在线制作视频的网站有哪些,电脑如何制作视频短片?
如何自定义建站之星网站的导航菜单样式?
山东云建站价格为何差异显著?
如何在IIS管理器中快速创建并配置网站?
如何通过西部数码建站助手快速创建专业网站?
建站之星Pro快速搭建教程:模板选择与功能配置指南
*请认真填写需求信息,我们会在24小时内与您取得联系。