资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

GridView在C#中如何导出Excel-创新互联

小编给大家分享一下GridView在C#中如何导出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 description for GridViewExport
 /// 
 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();
    }
   }
  }

  /// 
  /// Replace any of the contained controls with literals
  /// 
  /// 
  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);
    }
   }
  }

  /// 
  /// 导出Grid的数据(全部)到Excel
  /// 字段全部为BoundField类型时可用
  /// 要是字段为TemplateField模板型时就取不到数据
  /// 
  /// grid的ID
  /// 数据源
  /// 要导出Excel的文件名
  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("" + fileName + "");

   int count = grid.Columns.Count;

   s.Append("");
   s.AppendLine("");
   for (int i = 0; i < count; i++)
   {

    if (grid.Columns[i].GetType() == typeof(BoundField))
     s.Append("" + grid.Columns[i].HeaderText + "");

    //s.Append("" + grid.Columns[i].HeaderText + "");
   }
   s.Append("");
   foreach (DataRow dr in dt.Rows)
   {
    s.AppendLine("");
    for (int n = 0; n < count; n++)
    {
     if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
      s.Append("" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "");
    }
    s.AppendLine("");
   }

   s.Append("");
   s.Append("");

   page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));
   page.Response.End();
  }
 }
}

以上是“GridView在C#中如何导出Excel”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联成都网站设计公司行业资讯频道!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享文章:GridView在C#中如何导出Excel-创新互联
文章网址:http://cdkjz.cn/article/depsss.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220