1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 简单实现网页另存为word或者excel

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

时间:2019-09-30 02:36:47

相关推荐

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

最近在弄网页的导出,在网上找了很多的方法,最后用一种较为简单的方法实现,这次的寻找和解决问题的过程使我加深了对封装和面向对对象的理解更加深刻!在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){//ExcelResponse.AppendHeader("Content-Disposition", "attachment;filename=result.xls");Response.ContentType = "application/ms-excel";}else if (type == DocumentType.Word){//WordResponse.AppendHeader("Content-Disposition", "attachment;filename=result.doc");Response.ContentType = "application/ms-word";}//指定编码格式——utf-8是网页默认格式,word出现乱码是因为它的默认格式不是utf-8是gb2312Response.Charset = "utf-8";Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//关闭控件的视图状态source.Page.EnableViewState = false;//初始化HtmlWriterSystem.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);}

这个简单例子的解决是一种积累,主要解决了我们不知道的问题,让我们意识到自己哪些问题,该去找哪些类!在面向对象的今天,我们的解决思路,也许仅仅是,知道多一点!了解多一点!然后上网查!最后是熟悉和掌握!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。