asp.net 實現線上瀏覽word文檔(word轉html),
最近在做word文檔線上瀏覽,找了種種方法、控制項之後,迴歸到word轉HTML,線上瀏覽....
一下是後台代碼,前台html頁面預設代碼即可。
因為用檔案如下:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using Word = Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
沒有引用好組件時,此處會報錯,找不到Interop之類的,
這時需要在引用裡面引用組件.net下的Microsoft.Office.Interop.Visio,Microsoft.Office.Interop.Word
後台代碼如下:
protected void Page_Load(object sender, EventArgs e) { string relativePath = Request.QueryString["FilePath"]; //相對路徑 ,從跳轉頁面得到檔案相對路徑。 if (relativePath == "" || relativePath==null) return; string serverPath = Server.MapPath(relativePath); //相對轉伺服器對應路徑 string html = serverPath.Replace(".doc", ".html"); if (!File.Exists(@html)) //html頁面不存在,把word轉換成html { string filename = WordToHtml(serverPath); StreamReader fread = new StreamReader(filename, System.Text.Encoding.GetEncoding("gb2312")); string ss = fread.ReadToEnd(); Response.Write(ss); //直接寫字串到網頁會發現,文字可顯示,圖片、表格無法顯示。因此在後面重跳轉到html檔案頁面。 fread.Close(); fread.Dispose(); } html = relativePath.Replace(".doc", ".html"); //html檔案也儲存在同樣的路徑下, //只需要改了原路徑的尾碼即可得到html檔案路徑 Response.Redirect(html); return; } /// <summary> /// word轉成html /// </summary> /// <param name="wordFileName"></param> private string WordToHtml(object wordFileName) { //在此處放置使用者代碼以初始化頁面 Word.Application word = new Word.Application(); Type wordType = word.GetType(); Word.Documents docs = word.Documents; //開啟檔案 Type docsType = docs.GetType(); Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true }); //轉換格式,另存新檔 Type docType = doc.GetType(); string wordSaveFileName = wordFileName.ToString(); string strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html"; object saveFileName = (object)strSaveFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); return saveFileName.ToString(); }