word转html预览

2018/07/16 14:10
阅读数 49
#region Index页面
        /// <summary>
        /// Index页面
        /// </summary>
        /// <paramname="url">例:/uploads/......XXX.xls</param>
        public ActionResult PreviewWord()
        {
            string url =Request.QueryString["url"];
            //物理路径
            string physicalPath = Server.MapPath(Server.UrlDecode(url));
            string extension = Path.GetExtension(physicalPath);

            string htmlUrl = "";
            switch (extension.ToLower())
            {
                case ".doc":
                case ".docx":
                    htmlUrl = PreviewWordView(physicalPath, url);
                    break;

            }
            switch (extension.ToLower())
            {
                case ".pdf":
                    htmlUrl = physicalPath;
                    break;

            }

            return Redirect(Url.Content(htmlUrl));
        }
        #endregion

        #region 预览word文档(doc转html版)
        public string PreviewWordView(string physicalPath,string url)
        {
            Microsoft.Office.Interop.Word._Application application = null;
            Microsoft.Office.Interop.Word._Document doc = null;
            application = new Microsoft.Office.Interop.Word.Application();
            object missing = Type.Missing;
            object trueObject = true;
            application.Visible = false;
            application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            doc = application.Documents.Open(physicalPath, missing, trueObject, missing, missing, missing,
                   missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            //保存为html
            object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
            string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
            String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
            doc.SaveAs(outputFile, format, missing, missing, missing,
                                  missing, XlSaveAsAccessMode.xlNoChange, missing,
                                  missing, missing, missing, missing);
            //关闭文档对象
            doc.Close();
            //关闭应用程序对象
            application.Quit();
            //杀进程,有的情况下,关闭word文档会不成功,会残留很多word进程
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
            foreach (System.Diagnostics.Process p in processes)
            {
                bool b = p.MainWindowTitle == "";
                if (p.MainWindowTitle == "")
                {
                    p.Kill();
                }
            }
            return Path.GetDirectoryName(Server.UrlDecode(url))+"\\"+htmlName;
        }

        #endregion

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部