说明:此类是集合了网上朋友的一些类方法拼写而成,发表出来一便朋友们借鉴
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/*/时间:2010年2月6日
//文件:ExcelEdit.cs
//功能:定制griedview控件的表头,并能够导出Excel
//作者:门剑勇
//声明:此类是集合了网上的一些资料,并注明出处。加入了部分自己写的东东*/
/// <summary>
/// ExcelEdit 的摘要说明
/// 注意事项一:在调用此类的页添加下列方法
/// public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
/// {
/// //什么都没有,空的函数
/// }
///
/// 注意事项二:
/// SplitTableHeader函数是用在GridView控件的RowCreated事件中,调用方法如下例子:
/// protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
/// {
/// if (e.Row.RowType == DataControlRowType.Header)
/// {
/// ExcelEdit dHelper = new ExcelEdit();
/// string header = "等级#级别#上期结存 件数,重量,比例#本期调入 收购调入 件数,重量,比例#本期发出 车间投料 件数,重量,比例#本期发出 产品外销百分比 件数,重量,比例#平均值";
/// dHelper.SplitTableHeader(e.Row, header);
/// }
/// }
///
/// 注意事项三:
/// ModifygrdHeader函数,详细看函数说明。
/// </summary>
public class ExcelEdit
{
/// <summary>
/// ExcelEdit类构造函数
/// </summary>
public ExcelEdit()
{
}
/// <summary>
/// 定义dataset属性
/// </summary>
private DataSet _DS;
public DataSet DS
{
set { _DS = value; }
get { return _DS; }
}
/// <summary>
/// 定义GridView属性
/// </summary>
private GridView _GV;
public GridView GV
{
set { _GV = value;}
get { return _GV; }
}
/// <summary>
/// 绑定数据源,成功返回true,失败返回false。
/// </summary>
private bool BindGridView()
{
try
{
//定义GirdView的格式后,绑定数据源。
_GV.AllowPaging = false;
_GV.DataSource = _DS;
_GV.DataBind();
}
catch (Exception e)
{
//错误跳转到指定的错误页面
return false;
string url = HttpContext.Current.Request.ApplicationPath + "/error.aspx?error=" + e.Message.ToString() + "&strurl=" + HttpContext.Current.Request.Url.ToString();
HttpContext.Current.Response.Redirect(url);
}
//函数成功
return true;
}
/// <summary>
/// 导出GridView控件中的数据Excel
/// </summary>
public void toExcelgrdExcel()
{
if (BindGridView())
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Qty.xls");
//如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//设置输出文件类型为excel文件。
HttpContext.Current.Response.ContentType = "application/ms-excel";
//定义文件流,和控件输出流,建立关联。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.Html32TextWriter oHtmlTextWriter = new Html32TextWriter(oStringWriter);
//将控件的信息写到输出流。
_GV.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Output.Write(oStringWriter.ToString());