using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Web
{
//作者:林宏权 2015/12/31 00:16
/// <summary>
/// 扩展GridView导出Excel功能
/// </summary>
public partial class ExportGridView : GridView
{
/// <summary>
/// 数据库连接字符串
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// 命令文本
/// </summary>
public string SqlCmdText { get; set; }
/// <summary>
/// 主键字段
/// </summary>
public string[] PrimaryKey { get; set; }
/// <summary>
/// 导出的Excel文件名
/// </summary>
public string ExcelFileName { get; set; }
/// <summary>
/// 导出分页数据
/// </summary>
public bool ExportPagging { get; set; }
public ExportGridView()
{
}
public ExportGridView(string connectString,string cmd,string[] keys)
{
//启用分页
AllowPaging = true;
//启用排序
AllowSorting = true;
//数据源
DataSource = new SqlDataSource(connectString, cmd);
//主键字段
DataKeyNames = keys;
//导出分页数据(默认导出分页数据)
ExportPagging = true;
}
/// <summary>
/// 网页表格导出到Excel文件f
/// </summary>
/// <param name="fileName">导出的文件名</param>
public void GridViewToExcel( string fileName)
{
//启用分页
AllowPaging = false;
//启用排序
AllowSorting = false;
//重新绑定数据源
DataBind();
//字符集编码
HttpContext.Current.Response.Charset = "GB2312";
//内容编码
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
//文件名编码
var fileNameUtf8 = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
//添加Http头输出
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileNameUtf8);
//输出MIME类型
HttpContext.Current.Response.ContentType = "application/ms-excel";
//关闭页面与服务器控件的视图状态
EnableViewState = false;
//输出服务器控件(GridView)的内容到HtmlTextWriter
//==============================================
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
RenderControl(hw);
//==============================================
//http输出(Excel)文件
HttpContext.Current.Response.Write(tw.ToString());
//发送到客户端
HttpContext.Current.Response.End();
}
}
}