asp.net 實現在線瀏覽word文檔(word轉html)
來源:程序員人生 發布時間:2014-12-13 09:12:34 閱讀次數:3067次
最近在做word文檔在線閱讀,找了種種方法、控件以后,回歸到word轉HTML,在線閱讀....
1下是后臺代碼,前臺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();
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈