C#将Word,Excel与Html,PDF互转

摘要:
PublicclassOfficeHelper{/////<summary˃////Word已转换为html///</summary˃///<paramname=“path”˃publicstaticstringWordToHtml(字符串路径){//在此处放置用户代码以初始化页面Word.Applicationword=newWord.Application();Typeword
public class OfficeHelper
    {
        /// <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转成pdf
        /// </summary>
        /// <param name="path"></param>
        public static string WordToPdf(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.Split('.').GetValue(0) + ".pdf";
                object saveFileName = (object) strSaveFileName;
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc,
                    new object[] {saveFileName, Word.WdSaveFormat.wdFormatPDF});
                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>
        /// Excel转成html
        /// </summary>
        /// <param name="path"></param>
        public static string ExcelToHtml(string path)
        {
            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 = path.Substring(0, path.LastIndexOf('.')) + ".html";
                object ofmt = Excel.XlFileFormat.xlHtml;
                workbook.SaveAs(htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing); // 进行另存为操作   
                return htmlFile.ToString();
            }
            catch
            {
                throw new Exception("文件转换出错");
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(true, Type.Missing, Type.Missing);
                }
                repExcel.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// 把Excel文件转换成PDF格式文件
        /// </summary>
        /// <param name="path">源文件路径</param>
        /// <returns>true=转换成功</returns>
        public static string ExcelToPdf(string path)
        {
            Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Excel.Application repExcel = new Excel.Application();
            Excel.Workbook workBook = null;
            try
            {
                string savePath = path.Substring(0, path.LastIndexOf('.')) + ".pdf";
                object target = savePath;
                workBook = repExcel.Application.Workbooks.Open(path, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

                workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                return savePath;
            }
            catch
            {
                throw new Exception("文件转换出错");
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                }
                repExcel.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }

免责声明:文章转载自《C#将Word,Excel与Html,PDF互转》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇R in action读书笔记(15)第十一章 中级绘图 之二 折线图 相关图 马赛克图共享内存与存储映射(mmap)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

SpringBoot + Redis + Shiro 实现权限管理(转)

概述 本文基于网上整理,为了实现将Shiro框架的session存储到redis里面,进而实现基于Niginx负载均衡,多站点部署; maven下shiro依赖 <!-- shiro --> <dependency> <groupId>org.apache.shiro</gr...

ANR的原理分析和简单总结

前言ANR(Application Not Responding),应用无响应,这个可能每个人都碰到过。 该篇主要简单总结下,ANR的几种常见类型(输入事件、广播接收器、Service、ContentProvider),以及ANR一般如何产生的及如何避免。 最后重点是通过源码 了解这几种类型 是如何产生ANR、超时时间是怎么来的、ANR后如何处理的等。 关...

关于c++正则表达式的用法

本人最近在做一个项目,这个项目里面有一个功能是这样的,要求这个项目中提供搜索功能,简单的说,如果里面输入1-10 11,15,27,39这个字符串,那么你就要从中找到1,2,3,4,5,6,7,8,9,10和11,15,27,39等等这些数字。我考虑了很久,决定使用正则表达式来做,采用的原因有两点:其一,因为考虑到范围的问题(比如说位数不能超过三位)这样的...

DOCTYPE html PUBLIC 指定了 HTML 文档遵循的文档类型定义

今天看到一篇CSS应用的一个友好搜索,我按网页上的代码复制、粘贴后预览时总达不到效果,而直接拷贝他的实例却能达到效果,开始以为书写顺序不对,于是调整书写顺序,还是不行,最后找到了我认为最没什么用处的第一行才发现真正起作用的竟然是<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN"...

C#格式化数值结果表

C#格式化数值结果表 字符 说明 示例 输出 C 货币 string.Format("{0:C3}", 2) $2.000 D 十进制 string.Format("{0:D3}", 2) 002 E 科学计数法 1.20E+001 1.20E+001 G 常规 string.Format("{0:G}", 2) 2 N 用...

记一次内存泄漏DUMP分析

自从进入一家创业公司以后,逐渐忙成狗,却无所收获,感觉自身的技术能力用武之地很少,工作生活都在业务逻辑中颠倒。 前些天线上服务内存吃紧,让运维把DUMP拿下来,分析一下聊以自慰。 先来统计一下大对象信息 0:000> !dumpheap -min 85000 -stat Statistics: MT Count...