您的位置:首页 > 其它

简单实现网页另存为word或者excel

2017-07-26 00:00 211 查看
最近在弄网页的导出,在网上找了很多的方法,最后用一种较为简单的方法实现,这次的寻找和解决问题的过程使我加深了对封装和面向对对象的理解更加深刻!在B/S阶段,有很多已经封装好的类,而且在所有的页面都是一个个的类,只是我们使用的太频繁,也是不联系在一起忽视了他们!比如今天的问题,其实就是对io类的一个使用!

首先:我们在我们的页面层要添加一个属性:



<%@ PageLanguage="C#" AutoEventWireup="true"CodeBehind="printPage.aspx.csEnableEventValidation="false" Inherits="ExamSystemV3.Web.Student.printPage" %>
里将EnableEventValidation值设置为false主要是避免导出页面时进行安全验证,让其保证导出的顺利进行!

然后我们在页面后台添加一个方法:

public void ExpertControl(System.Web.UI.Control source, DocumentType type)
{
//设置Http的头信息,编码格式
if (type == DocumentType.Excel)
{
//Excel
Response.AppendHeader("Content-Disposition", "attachment;filename=result.xls");
Response.ContentType = "application/ms-excel";
}
else if (type == DocumentType.Word)
{
//Word
Response.AppendHeader("Content-Disposition", "attachment;filename=result.doc");
Response.ContentType = "application/ms-word";
}
//指定编码格式——utf-8是网页默认格式,word出现乱码是因为它的默认格式不是utf-8是gb2312
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
//关闭控件的视图状态
source.Page.EnableViewState = false;
//初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter);
//输出
Response.Write(writer.ToString());
Response.End();
}
//文档类型枚举
public enum DocumentType
{
Word,
Excel
}


最后,在使用的时候调用:
例如:我们增加了一个导出的按钮:

protected void Button1_Click(object sender, EventArgs e)
{

ExpertControl(this, DocumentType.Word);

}


这个简单例子的解决是一种积累,主要解决了我们不知道的问题,让我们意识到自己哪些问题,该去找哪些类!在面向对象的今天,我们的解决思路,也许仅仅是,知道多一点!了解多一点!然后上网查!最后是熟悉和掌握!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐