码迷,mamicode.com
首页 > 其他好文 > 详细

使用服务器端控件(GridView)进行数据导出(Excel和Word)

时间:2015-03-11 17:00:55      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

1.我使用三层做的,在DAL和BLL中引用System.Web;命名空间

2.写三层方法       

#region 额外
/// <summary>
/// 导出Excel和导出Word的方法
/// </summary>
/// <param name="gv">要导出的数据</param>
/// <param name="fileType">导出数据的文档类型</param>
/// <param name="fileName">导出数据的文档扩展名</param>
public void Export(GridView gv, bool fileType, string fileName)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Buffer = true;
response.Charset = "GB2312";
response.Write("<meta http-equiv=Content-Type context=‘text/html‘;>");
response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());//fileName.xls
response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
if (fileType == true)
{
response.ContentType = "application/excel";//输出类型为excel
}
else
{
response.ContentType = "application/word";//输出类型为excel
}
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
response.Output.Write(sw.ToString());
response.Flush();
response.End();
}
#endregion

 

3.在UI层中进行调用

TUserBLL bll = new TUserBLL();
TUserDAL dal = new TUserDAL();
protected void Page_Load(object sender, EventArgs e)
{

}
public override void VerifyRenderingInServerForm(Control control)
{

//这个重写方法是必须的,不用实现即可
}
protected void btnExcel_Click(object sender, EventArgs e)
{
bll.Export(gvExcelAndWord, true, "用户信息表.xls");
}

protected void btnWord_Click(object sender, EventArgs e)
{
bll.Export(gvExcelAndWord, false, "haha.doc");
}

4.特殊说明:在UI层中调用的时候必须做两个操作

4.1在.cs后台页面写上这个重写方法

public override void VerifyRenderingInServerForm(Control control)
{

//这个重写方法是必须的,不用实现即可
}

4.2在前台页面修改为不需要执行事件验证 EnableEventValidation="false" 或者修改配置文件<pages enableEventValidation="false"></pages>

使用服务器端控件(GridView)进行数据导出(Excel和Word)

标签:

原文地址:http://www.cnblogs.com/zzuhero/p/4330070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!