Office转HTML

    /// <summary>
        /// word转成html
        /// </summary>
        /// <param name="path"></param>
        public static string WordToHtml(string path)
        {
            //在此处放置用户代码以初始化页面
            Word.Application word = new Word.Application();
            Type wordType = word.GetType();
            Word.Documents docs = word.Documents;
            Type docsType = docs.GetType();
            try
            {
                Word.Document doc =(Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs,new Object[] {path, true, true});
                //转换格式,另存为
                Type docType = doc.GetType();
                string strSaveFileName = path.Substring(0, path.LastIndexOf('.')) + ".html";
                object saveFileName = (object) strSaveFileName;
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc,
                    new object[] {saveFileName, Word.WdSaveFormat.wdFormatHTML});
                docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
                return saveFileName.ToString();
            }
            catch
            {
                throw new Exception("文件转换出错");
            }
            finally
            {
                //退出 Word
                wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// word转成html带分页
        /// </summary>
        /// <param name="path"></param>
        /// <param name="id"></param>
        public static ResultDTO WordToHtmls(string path, string id)
        {
            FileInfo f = new FileInfo(path);
            if (!f.Exists)
                return null;

            var basePath = path.Substring(0,path.IndexOf("DownLoads", StringComparison.Ordinal));
            //转换文件根路径
            string root = basePath + "DownLoads/Html/";
            if (!Directory.Exists(@root + id))
            {
                Directory.CreateDirectory(@root + id);
            }

            Word.Document doc = null;
            var pages = "";
            Word.Application word = new Word.Application();
            Type wordType = word.GetType();
            Word.Documents docs = word.Documents;
            Type docsType = docs.GetType();
            try
            {
                object oMissing = System.Reflection.Missing.Value;
                doc =(Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs,new Object[] {path, true, true});
                bool flag = true;
                int index = 1;
                do
                {
                    object objWhat = Word.WdGoToItem.wdGoToPage;
                    object objWhich = Word.WdGoToDirection.wdGoToAbsolute;
                    object objPage = index;
                    Word.Range range1 = doc.GoTo(ref objWhat, ref objWhich, ref objPage, ref oMissing);
                    Word.Range range2 = range1.GoToNext(Word.WdGoToItem.wdGoToPage);
                    object objStart = range1.Start;
                    object objEnd = range2.Start;
                    if (range1.Start == range2.Start)
                    {
                        objEnd = range2.StoryLength;
                        flag = false;
                    }

                    doc.Range(ref objStart, ref objEnd).Copy();
                    Word.ApplicationClass wordapp = new Word.ApplicationClass();
                    Word.Document doc2 = wordapp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                    Word.Paragraph para = doc2.Content.Paragraphs.Add(ref oMissing);
                    para.Range.Paste();
                    var pagepath = id + "/" + index + ".html";
                    doc2.GetType().InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc2,
                        new object[] {root + pagepath, Word.WdSaveFormat.wdFormatHTML});
                    wordapp.GetType().InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, wordapp, null);
                    pages += pagepath + ",";
                    index++;
                } while (flag);

                object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
                doc.Close(ref saveOption, ref oMissing, ref oMissing);
                return new ResultDTO
                {
                    status = true,
                    info = pages.Substring(0, pages.Length - 1)
                };
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return new ResultDTO
                {
                    status = false,
                    info = e.Message
                };
            }
            finally
            {
                wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// Excel转成html
        /// </summary>
        /// <param name="path"></param>
        /// <param name="id"></param>
        public static ResultDTO ExcelToHtml(string path,string id)
        {
            FileInfo f = new FileInfo(path);
            if (!f.Exists)
                return null;

            var basePath = path.Substring(0, path.IndexOf("DownLoads", StringComparison.Ordinal));
            //转换文件根路径
            string root = basePath + "DownLoads/Html/";
            if (!Directory.Exists(@root + id))
            {
                Directory.CreateDirectory(@root + id);
            }

            Excel.Application repExcel = new Excel.Application();//实例化Excel
            Excel.Workbook workbook = null;
            try
            {
                workbook = repExcel.Application.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                object htmlFile =id + "/" + id + ".html"; 
                object ofmt = Excel.XlFileFormat.xlHtml;
                workbook.SaveAs(root + htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing); // 进行另存为操作   
                return new ResultDTO
                {
                    status = true,
                    info = htmlFile.ToString()
                };
            }
            catch(Exception e)
            {
                log.Error(e.Message);
                return new ResultDTO
                {
                    status = false,
                    info = e.Message
                };
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(true, Type.Missing, Type.Missing);
                }
                repExcel.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }

    /// <summary>
    /// 输出结果
    /// </summary>
    public class ResultDTO
    {
        public bool status; //状态
        public string info; //详情
    }
注:此处获取文档页数不可用以下方法获取,因为它表示的页数是指页面视图的页大小,并不是页面视图的页大小。
                Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                file_pages = doc.ComputeStatistics(stat, ref missing);
posted @ 2016-04-17 22:05  徐航  阅读(446)  评论(0编辑  收藏  举报