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>