栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#导出GridView数据到Excel文件类实例

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#导出GridView数据到Excel文件类实例

本文实例讲述了C#导出GridView数据到Excel文件类。分享给大家供大家参考。具体如下:

这段C#代码自定义了一个封装类,用于将GridView数据导出到Excel文件

using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
namespace DotNet.Utilities
{
  public class ExportExcel
  {
    protected void ExportData(string strContent, string FileName)
    {
      FileName = FileName + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.Charset = "gb2312";
      HttpContext.Current.Response.ContentType = "application/ms-excel";
      HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
      //this.Page.EnableViewState = false;
      // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
      HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
      // 把文件流发送到客户端
      HttpContext.Current.Response.Write("");
      HttpContext.Current.Response.Write(strContent);
      HttpContext.Current.Response.Write("");
      // 停止页面的执行
      //Response.End();
    }
    /// 
    /// 导出Excel
    /// 
    /// 
    public void ExportData(GridView obj)
    {
      try
      {
 string style = "";
 if (obj.Rows.Count > 0)
 {
   style = @" .text { mso-number-format:@; }  ";
 }
 else
 {
   style = "no data.";
 }
 HttpContext.Current.Response.ClearContent();
 DateTime dt = DateTime.Now;
 string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
 HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportData" + filename + ".xls");
 HttpContext.Current.Response.ContentType = "application/ms-excel";
 HttpContext.Current.Response.Charset = "GB2312";
 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
 StringWriter sw = new StringWriter();
 HtmlTextWriter htw = new HtmlTextWriter(sw);
 obj.RenderControl(htw);
 HttpContext.Current.Response.Write(style);
 HttpContext.Current.Response.Write(sw.ToString());
 HttpContext.Current.Response.End();
      }
      catch
      {
      }
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/125632.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号