最近做項目用到了將整個頁面導出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(); }
模板文件
二、dsoframer的方式晚上再弄吧。趕緊工作了