当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现GridView导出Excel实例代码

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

导出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();
  }

 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网