在我們的日常生活中,使用word來編輯文本是很常見的,我們的程序員在編寫程序的時候,會用文本或word文件編寫網頁代碼,下面錯新技術頻道小編給大家帶來Asp.net中將Word文件轉換成HTML的方法。
關鍵代碼如下:
//存放word文件的完整路徑 string wordPath = Server.MapPath("/word/test.doc"); //存放html文件的完整路徑 string htmlPath = Server.MapPath("/html/test.html"); //上傳word文件, 由于只是做示例,在這里不多做文件類型、大小、格式以及是否存在的判斷 FileUpload1.SaveAs(wordPath); #region 文件格式轉換 //請引用Microsoft.Office.Interop.Word ApplicationClass word = new ApplicationClass();Type wordType = word.GetType();Documents docs = word.Documents; //打開文件 Type docsType = docs.GetType(); object fileName = wordPath; //"f://cc.doc"; Document doc =(Document)docsType.InvokeMember("Open", BindingFlags.InvokeMethod, null, (object)docs, new Object[] { fileName, true, true}); //判斷與文件轉換相關的文件是否存在,存在則刪除。(這里,最好還判斷一下存放文件的目錄是否存在,不存在則創建) if(File.Exists(htmlPath)) { File.Delete(htmlPath); } //每一個html文件,有一個對應的存放html相關元素的文件夾(html文件名.files) if(Directory.Exists(htmlPath.Replace(".html" ,".files"))) { Directory.Delete(htmlPath.Replace(".html", ".files"), true); }; //轉換格式,調用word的“另存為”方法 Type docType =doc.GetType(); object saveFileName = htmlPath; //"f://aaa.html"; docType.InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML }); //退出 Word wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null); #endregion上述代碼,在.net framework4.0 中,可能會出一編譯錯誤,如下所示:
無法嵌入互操作類型“……”,請改用適用的接口。
經過查閱資料,找到解決方案如下:
選中項目中引入word的dll,鼠標右鍵,選擇屬性,把“嵌入互操作類型”設置為False。
以上就是錯新技術頻道小編為大家帶來的Asp.net中將Word文件轉換成HTML的方法,當然錯新技術頻道還有非常多專業知識,歡迎大家收藏。
新聞熱點
疑難解答
圖片精選