打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
(22)关于HTML转DOC
       恩,现在有这个需求,就是需要html方便的模板和样式,但是又需要一般用户也可以方便的编辑,那么我想到了html2doc,虽然方法不是很完美,但是可以满足我们纯文本格式htm(文字、表格等)到doc的转换。
    借助C#调用officePIA可以轻松地完成这个工作,原理其实就是我们用ms word可以打开htm文件并进行另存为doc。
   不多说,俗一点,全程贴代码,
   需要补一下using和引用Microsoft.Office.Interop.Word这个dll(word的pia):

static void Main(string[] args)
       {
          string inputName = Console.ReadLine(); //打开文件的位置
          string ext = Path.GetExtension(inputName);
          string outputName =inputName.Replace(ext,".doc"); // 同路径保存

          if(File.Exists(inputName))
          {
                 
              objectoMissing = System.Reflection.Missing.Value;
              objectoTrue = true;
              objectoFalse = false;

             Microsoft.Office.Interop.Word._Application oWord= new Microsoft.Office.Interop.Word.Application();
             Microsoft.Office.Interop.Word._Document oWordDoc= new Microsoft.Office.Interop.Word.Document();

             oWord.Visible = false;

// 这里是打开文件的扩展名
              objectopenFormat =Microsoft.Office.Interop.Word.WdOpenFormat.wdOpenFormatWebPages; 

              objectopenName = inputName;

          
              oWordDoc =oWord.Documents.Open(ref openName, ref oMissing, ref oTrue, refoMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref openFormat, ref oMissing, ref oMissing, refoMissing, ref oMissing, ref oMissing, ref oMissing);


              objectsaveFileName = outputName;

// 这里是保存文件的扩展名
              objectsaveFormat =Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

             oWordDoc.SaveAs(ref saveFileName, ref saveFormat,ref oMissing, ref  oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref  oMissing, ref oMissing, ref  oMissing, ref oMissing, ref  oMissing, ref oMissing, ref  oMissing);

             oWordDoc.Close(ref oTrue, ref oMissing, refoMissing);
             oWord.Quit(ref oTrue, ref oMissing, refoMissing);
          }
       }

这段代码实现了在命令行里输入一个htm的绝对路径,将其自动转换为doc,要求就是htm是文本格式的,不带图片什么乱七八糟的,表格没问题,依赖msoffice。

-----------------------------------------------------------------------------------------
附更加无耻的方法,完全不依赖 MS office! 你猜到了吗?
就是直接将htm格式的文本保存为以.doc为扩展名的文件!
原因很简单,现在兼容doc的软件,包括ms office都可以打开htm的文件,即识别html代码。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#操作Word中的表格
关于用Word.Application 打开了多个word文档时,出错,说Normal.dotm正由另一程序占用或者用户占用 解决方法
C#编程技巧:读取Word的方法
(转)C# Office操作
c#获取txt,word,excel文档内容方法
CSDN 论坛
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服