当前位置:软件学习 > Word >>

Asp.net导出word的方法总结(利用response.write方式将html模板导出word,和dsoframer导出word)

最近做项目用到了将整个页面导出word,原来用的dsoframer,发现导出的时候格式不是很好,随找了一个html模板方式导出word,现写出来供大家参考,并将步骤说与大家:
1、新建一个word文档,做成一个模板,需要填充数据库内容的地方用诸如{Year}的方式标记。
2、点击文件--另存为网页,起一个名字。比如xx.htm,关闭。
3、打开刚刚保存的htm文件,打开方式选择word,你会发现。打开的时候视图方式改为了 web,这让我们开着很不爽,虽然打印的时候没啥问题,但是总是感觉不爽,经过研究,发现可以这么操作,点击视图页面,这个word文档就变成了视图方式,合乎常理的,但是现在保存再打开,发现word一点没改变,别着急,重新打开这个模板文档,然后点击视图页面--随便在页面上打一个空格,然后保存,就可以了。哈
4、对于cs的页面文件,我把内容贴出来
 protected void btnShow_Click( object sender, EventArgs e )
    {
        string strWord = ExprotMissionToWord( Server.MapPath( "~/download/magazineturn.htm" ) );
        //Response Word File To Client                
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader( "content-disposition", "attachment;filename=magazineturn.doc" ); //必须的
        Response.AddHeader( "Content-type", "application" );
        Response.ContentType = "application/ms-html";
        Response.ContentEncoding = System.Text.Encoding.Default; //如果不行改为utf7,默认一般可以,处理头部乱码的问题
         Response.Write( strWord );
        Response.Flush();
        Response.Close();
    }
    public string ExprotMissionToWord( string templatePath )
    {
        StringBuilder sb = new StringBuilder( 1024 );
        if (Request["magazineTurnID"] == null)
        {
            WebUtilities.HandleMessage( this.Page, "对不起,未流转的不能导出" );
        }
        else
        {
            MagazineTurn mt = this.magazineTurnService.GetMagazineTurnByID( Request["magazineTurnID"].ToString() );
            StreamReader sr = new StreamReader( templatePath, Encoding.Default );
            sb.Append( sr.ReadToEnd() );
            sr.Close();
            sb.Replace( "{Year}", mt.DCreatedTime.ToString( "yyyy" ) );
            sb.Replace( "{Issue}", mt.Id );
            sb.Replace( "{SourceID}", mt.SourceID );
            sb.Replace( "{Content}", mt.TurnContent );
            sb.Replace( "{FromUnit}", this.unitInfoService.Get( mt.TurnFromUnitName ).Name );
            sb.Replace( "{FromUser}", mt.TurnFromUserName );
            sb.Replace( "{LeaderReplay}", mt.TurnLeaderReplay );
            sb.Replace( "{ToUnit}", this.unitInfoService.Get( mt.TurnToUnitName ).Name );
            sb.Replace( "{LimitTime}", mt.TurnLimitTime.ToString("yyyy年MM月dd日 HH:mm:ss") );
            sb.Replace( "{FeedBackResults}", mt.TurnFeedBackResults );
            sb.Replace( "{FeedBacker}", mt.TurnFeedBacker );
            sb.Replace( "{responsibility}", mt.TurnToUserName );
        }
        return sb.ToString();
    }
 <A href="/2012/0417/20120417091146755.rar">模板文件</A>

 二、dsoframer的方式晚上再弄吧。赶紧工作了

 

摘自 倚楼听雨
补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,