C#实现GridView导出Excel实例代码

发布时间 - 2026-01-11 00:27:50    点击率:

导出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 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 如何将凡科建站内容保存为本地文件?  手机网站制作平台,手机靓号代理商怎么制作属于自己的手机靓号网站?  网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?  企业网站制作这些问题要关注  ai格式如何转html_将AI设计稿转换为HTML页面流程【页面】  Laravel Blade模板引擎语法_Laravel Blade布局继承用法  html5如何设置样式_HTML5样式设置方法与CSS应用技巧【教程】  实例解析angularjs的filter过滤器  使用C语言编写圣诞表白程序  Laravel如何创建自定义Facades?(详细步骤)  Linux虚拟化技术教程_KVMQEMU虚拟机安装与调优  WEB开发之注册页面验证码倒计时代码的实现  Python制作简易注册登录系统  长沙企业网站制作哪家好,长沙水业集团官方网站?  Java垃圾回收器的方法和原理总结  如何在阿里云完成域名注册与建站?  Laravel的路由模型绑定怎么用_Laravel Route Model Binding简化控制器逻辑  如何在Windows服务器上快速搭建网站?  Android okhttputils现在进度显示实例代码  Laravel Blade组件怎么用_Laravel可复用视图组件的创建与使用  Windows10如何删除恢复分区_Win10 Diskpart命令强制删除分区  js代码实现下拉菜单【推荐】  javascript读取文本节点方法小结  如何在云主机快速搭建网站站点?  Laravel如何使用集合(Collections)进行数据处理_Laravel Collection常用方法与技巧  Laravel storage目录权限问题_Laravel文件写入权限设置  Laravel怎么使用Markdown渲染文档_Laravel将Markdown内容转HTML页面展示【实战】  Android 常见的图片加载框架详细介绍  浏览器如何快速切换搜索引擎_在地址栏使用不同搜索引擎【搜索】  html5的keygen标签为什么废弃_替代方案说明【解答】  bootstrap日历插件datetimepicker使用方法  在Oracle关闭情况下如何修改spfile的参数  在线制作视频的网站有哪些,电脑如何制作视频短片?  网易LOFTER官网链接 老福特网页版登录地址  Laravel辅助函数有哪些_Laravel Helpers常用助手函数大全  Laravel与Inertia.js怎么结合_使用Laravel和Inertia构建现代单页应用  Laravel如何使用Sanctum进行API认证?(SPA实战)  HTML 中如何正确使用模板变量为元素的 name 属性赋值  如何在建站主机中优化服务器配置?  微博html5版本怎么弄发语音微博_语音录制入口及时长限制操作【教程】  网站制作企业,网站的banner和导航栏是指什么?  如何在云指建站中生成FTP站点?  音乐网站服务器如何优化API响应速度?  如何用ChatGPT准备面试 模拟面试问答与职场话术练习教程  悟空识字如何进行跟读录音_悟空识字开启麦克风权限与录音  Python数据仓库与ETL构建实战_Airflow调度流程详解  Android Socket接口实现即时通讯实例代码  Laravel如何将应用部署到生产服务器_Laravel生产环境部署流程  如何在局域网内绑定自建网站域名?  Laravel怎么实现API接口鉴权_Laravel Sanctum令牌生成与请求验证【教程】