HTML转为office WORD方案_html 转 word_笨笨D幸福的博客-程序员宅基地

技术标签: c#  错误收集  

HTML2Word

目前转换html与word有很多方案,这里只说明windows下的。

  1. 使用HtmlToOpenXml库,直接转换,问题是只支持基础的,不支持CSS(效果一般)
  2. 使用Xceed收费版,insertContent, 自带RTF/HTML转换功能(没用过)
  3. 使用Office自带的打开和另存为功能,间接转换。(效果最接近)

参考代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xceed.Words.NET;
using Xceed.Document.NET;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using HtmlToOpenXml;
using MSWord = Microsoft.Office.Interop.Word;

namespace docxdemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 将一个文档合并到另外一个里面
            using (var document = DocX.Load("file1.docx"))
            {
                // goto end of document
                

                for(var i = 0; i < 3; i++) { 
                    using (var document2 = DocX.Load("file2.docx"))
                    {
                        // Insert a document at the end of another document.
                        // When true, document is added at the end. When false, document is added at beginning.
                        document.InsertDocument(document2, true, false, MergingMode.Local);

                    }
                }

                // Save the changes to the document
                document.SaveAs("demo.docx");

                System.Diagnostics.Process.Start("demo.docx");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 通过第三方库将html转换为word
            const string filename = "file2.docx";
            string html = textBox1.Text;

            if (File.Exists(filename)) File.Delete(filename);

            using (MemoryStream generatedDocument = new MemoryStream())
            {
                using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = package.MainDocumentPart;
                    if (mainPart == null)
                    {
                        mainPart = package.AddMainDocumentPart();
                        new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart);
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);
                    converter.ParseHtml(html);

                    mainPart.Document.Save();
                }

                File.WriteAllBytes(filename, generatedDocument.ToArray());
            }

            System.Diagnostics.Process.Start(filename);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // 通过office自带的功能将html转换为word
            string source = "demo.htm";
            string target = "./msdemo.docx";

            using (var ht = File.Open(source, FileMode.OpenOrCreate))
            {
                var txt = $"<html>{ textBox1.Text}</html>";
                var buff = Encoding.UTF8.GetBytes(txt);
                ht.Write(buff, 0, buff.Length);
                ht.Close();
            }


            MSWord._Application newApp = new MSWord.Application();
            //try
            //{
            //    this.app = (Application)Microsoft.VisualBasic.Interaction.GetObject(null, "Word.Application");
            //}
            //catch
            //{
            //    this.app = new Application();
            //}
            MSWord.Documents d = newApp.Documents;
            object Unknown = Type.Missing;
            object format = MSWord.WdOpenFormat.wdOpenFormatWebPages;  //Microsoft.Office.Interop.Word.WdOpenFormat
            object enc = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8; //msoEncodingAutoDetect;

            object src = Path.GetFullPath("./demo.htm");
            MSWord.Document od = d.Open(ref src, false,
                                     ref Unknown, ref Unknown, ref Unknown,
                                     ref Unknown, ref Unknown, ref Unknown,
                                     ref Unknown, ref format, ref enc,
                                     ref Unknown, ref Unknown, ref Unknown, ref Unknown);


            object targ = Path.GetFullPath("./msdemo.docx");
            object format2 = MSWord.WdSaveFormat.wdFormatDocumentDefault;
            od.SaveAs2(targ, ref format2,
            //newApp.ActiveDocument.SaveAs(targ, ref format2,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown);

            od.Close(MSWord.WdSaveOptions.wdDoNotSaveChanges);
            newApp.Quit(MSWord.WdSaveOptions.wdDoNotSaveChanges);

            System.Diagnostics.Process.Start(targ.ToString());
        }
    }
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/bbdxf/article/details/120326998

智能推荐

微擎支付返回商户单号_关于聚合支付业务的2个核心功能_weixin_39951930的博客-程序员宅基地

聚合支付业务平台面向商户使用的核心功能包括商户进件入驻第三方支付或银行渠道、对账功能。商户进件商户要使用聚合支付,首先需要将入驻支付渠道所需的进件资料(进件资料需要仔细阅读支付渠道给的对接接口里需要提供的字段信息,细节方面有时需要和对接公司人员详细沟通)上传到网站,然后网站会将资料传给支付渠道,完成进件入驻流程;进件的主要目的是在具有支付牌照的支付渠道那里创建一个账户,用来收款分账。当然,聚合支付...

mac终端关机命令_yang3wei的博客-程序员宅基地

转载自:http://pulading1988.diandian.com/post/2012-04-22/173927011. 立即关机是sudo halt或者sudo shutdown -h now2. 10分钟后关机sudo shutdown -h +103. 晚上8点关机sudo shutdown -h 20:004. 立即重启sudo r

java脚本与jsp脚本的区别_JSP原理与脚本元素_网友李艾的博客-程序员宅基地

JSP(Java Server Page)使用环境:java webJSP的运行原理首先启动服务器,并且要保证应用在服务器上(把应用导出为WAR放在webapps下面,会自动解压加载)在客户端通过浏览器发送请求(在地址栏中输入地址)服务器接收到请求之后,查找有没有这个文件对应的Java文件的对象。如果没有这个对象,需要创建(先把JSP文件转换成Java文件,编译成.class文件,加载类并创建对象...

calc 多项式计算 (STL版和非STL版) -SilverN_a394121312的博客-程序员宅基地

计算(calc.cpp)【问题描述】小明在你的帮助下,破密了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”求出的值就是密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法)【输入】输入文件calc.in共1行,为一个算式。【输出】输出文件calc.out...

Android IOS WebRTC 音视频开发总结(七七)-- WebRTC的架构和协议栈_weixin_34400525的博客-程序员宅基地

Android IOS WebRTC 音视频开发总结(七七)-- WebRTC的架构和协议栈 本文主要介绍WebRTC的架构和协议栈(我们翻译和整理的,译者:litie),最早发表在【编风网】支持原创,转载必须注明出处,欢迎关注我的微信公众号blacker(微信ID:blackerteam 或 webrtcorgcn)。为了便于理...

随便推点

Android ImageView 加边框_victoryckl的博客-程序员宅基地

http://www.cnblogs.com/shadowjl/archive/2011/04/01/2002799.html直接看代码: 1 package shadow.widget; 2  3 import android.content

在vue.js中实现a标签href tel的打电话功能_a href={`tel:tele`}_人间草木96的博客-程序员宅基地

&amp;lt;div v-for=&quot;p in persons&quot;&amp;gt; &amp;lt;p&amp;gt; name: {{ p.name }} &amp;lt;/p&amp;gt; &amp;lt;p&amp;gt; //正确做法,拼接字符串 tel: &amp;lt;a :href=&quot;'tel:' + p.phone&quot;&amp;gt;call me&amp;lt;/a&amp;gt

各自然带代表植被_陆地自然带:从森林、草原到荒漠,具有非常复杂的地域差异性..._weixin_39702649的博客-程序员宅基地

地球表面可以分为海洋和陆地两大部分,其中陆地面积约为1.39亿平方千米,约占地球表面积的29.2%。陆地和海洋是两个完全不同的生态系统,陆地上的生物群落由于受到自然条件的限制,在分布上具有很强的差异性,也就是说在不同的区域会分布不同的生物群落。世界陆地自然带从高温多雨的赤道到冰雪覆盖的极地,从湿润的沿海到干燥的内陆,形成各种各样的自然地理环境。其中最能体现自然地理环境差异性的自然地理要素就是“陆地...

布局(三)——固定浮动布局_ruby小酱的博客-程序员宅基地

布局3——固定浮动布局,特点:3. 固定浮动布局  规格:固定大小,不能随着视窗改变  采用:浮动布局  兼容:兼容当前主流浏览器实践部分html代码css代码// 1.所谓固定浮动——固定大小,不能随着视窗改变// 2.固定——设置块状width为像素值// 3.中间两列的浮动——首先在两列下方在加一层块(div

【Web安全笔记】之【2.0 计算机网络与协议】_AA8j的博客-程序员宅基地

2.0 计算机网络与协议2.1 网络基础计算机通信网的组成计算机网络由通信子网和资源子网组成。其中通信子网负责数据的无差错和有序传递,其处理功能包括差错控制、流量控制、路由选择、网络互连等。其中资源子网是计算机通信的本地系统环境,包括主机、终端和应用程序等, 资源子网的主要功能是用户资源配置、数据的处理和管理、软件和硬件共享以及负载均衡等。总的来说,计算机通信网就是一个由通信子网承载的、传输和共享资源子网的各类信息的系统。通信协议为了完成计算机之间有序的信息交换,提出了通信协议的概念,其定义

跨站点脚本编制 - SpringBoot配置XSS过滤器(基于mica-xss)_C3Stones的博客-程序员宅基地

1. 简介  XSS,即跨站脚本编制,英文为Cross Site Scripting。为了和CSS区分,命名为XSS。  XSS是最普遍的Web应用安全漏洞。这类漏洞能够使得攻击者嵌入恶意脚本代码到正常用户会访问到的页面中,当正常用户访问该页面时,则可导致嵌入的恶意脚本代码的执行,从而达到恶意攻击用户的目的。2. XSS相关博客  跨站点脚本编制 - SpringBoot配置XS...