首页 > 其他分享 >使用 Open XML SDK 实现 html 富文本转换为 docx 格式示例

使用 Open XML SDK 实现 html 富文本转换为 docx 格式示例

时间:2023-10-12 21:12:15浏览次数:41  
标签:XML docx 示例 htmlContent HTML using new Document

 

使用 Open XML SDK 实现 html 富文本转换为 docx 格式文档相对复杂。下面是一个示例。手动检测 <strong>和 <em> 标签并应用相应的文本格式。

using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

class Program
{
    static void Main()
    {
        string htmlContent = "<p>This is <strong>bold</strong> and <em>italic</em> text.</p>";

        // 创建一个新的docx文档
        using (WordprocessingDocument doc = WordprocessingDocument.Create("output.docx", WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            Body body = mainPart.Document.AppendChild(new Body());

            // 解析HTML并创建docx段落
            string[] paragraphs = htmlContent.Split(new[] { "<p>", "</p>" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string paragraphContent in paragraphs)
            {
                Paragraph paragraph = new Paragraph();
                Run run = new Run();

                string[] tags = paragraphContent.Split(new[] { "<strong>", "</strong>", "<em>", "</em>" }, StringSplitOptions.None);
                foreach (string tag in tags)
                {
                    RunProperties runProperties = new RunProperties();
                    if (tag.Contains("<strong>"))
                    {
                        runProperties.Bold = new Bold();
                    }
                    if (tag.Contains("<em>"))
                    {
                        runProperties.Italic = new Italic();
                    }

                    run.Append(runProperties);
                    run.Append(new Text(tag));
                }

                paragraph.Append(run);
                body.Append(paragraph);
            }
        }

        Console.WriteLine("HTML to docx conversion complete.");
    }
}

 

 

需要根据 HTML 标记的不同来创建相应的 docx元素,例如将<p>标签映射到docx段落,将<strong>标签映射到粗体等。

using System;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

class Program
{
    static void Main()
    {
        string htmlContent = "<p>This is <strong>bold</strong> and <em>italic</em> text.</p>";

        // 创建一个新的docx文档
        using (WordprocessingDocument doc = WordprocessingDocument.Create("output.docx", WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            Body body = mainPart.Document.AppendChild(new Body());

            // 解析HTML内容并创建相应的docx元素
            ProcessHtmlContent(htmlContent, body);

            doc.Save();
        }

        Console.WriteLine("HTML to docx conversion complete.");
    }

    static void ProcessHtmlContent(string htmlContent, OpenXmlElement parentElement)
    {
        // 解析HTML内容并将其映射到docx元素
        // 这里需要根据HTML标记的不同来创建相应的docx元素
        // 例如,<p>标签可以映射到段落,<strong>可以映射到粗体文本等

        // 示例:将HTML段落转换为docx段落
        if (htmlContent.StartsWith("<p>") && htmlContent.EndsWith("</p>"))
        {
            string paragraphText = htmlContent.Substring(3, htmlContent.Length - 7);
            Paragraph paragraph = new Paragraph(new Run(new Text(paragraphText)));
            parentElement.Append(paragraph);
        }

        // 添加更多的HTML标记处理逻辑以满足你的需求
    }
}

 

标签:XML,docx,示例,htmlContent,HTML,using,new,Document
From: https://www.cnblogs.com/citycomputing/p/17760582.html

相关文章

  • powerjob 任务与工作流配置示例
    powerjob任务与工作流配置示例官方文档:https://www.yuque.com/powerjob/guidence/ysug77参数描述该截图来自项目官方文档:官方处理器(内置的任务处理器)官方文档:https://www.yuque.com/powerjob/guidence/official_processor官方源码:https://github.com/PowerJob/PowerJob/t......
  • 关于c语言操作libwebsockets示例
    第一步,安装libwebsockets库,c语言编写的,默认安装引用库,配置相应的库及路径第二步:上代码main.h ////CreatedbyAdministratoron2020/5/1.// #ifndefMEDIA_MAIN_H#defineMEDIA_MAIN_H #define boolchar volatileintexit_sig=0; #defineMAX_PAYLOAD_SIZE 10......
  • 【Azure Developer】在App Service上放置一个JS页面并引用msal.min.js成功获取AAD用户
    问题描述在AppService上放置一个JS页面并引用msal.min.js,目的是获取AAD用户名并展示。问题解答示例代码<!DOCTYPEhtml><html><head><title>AzureService</title></head><scripttype="text/javascript"src="https://alcdn.msauth.net/......
  • 【Azure Developer】在App Service上放置一个JS页面并引用msal.min.js成功获取AAD用户
    问题描述在AppService上放置一个JS页面并引用msal.min.js,目的是获取AAD用户名并展示。问题解答示例代码<!DOCTYPEhtml><html><head><title>AzureService</title></head><scripttype="text/javascript"src="https://alcdn.msauth.net/lib/1.......
  • 在Mac上安装lxml
    最近想开始学习一下爬虫,用来截取一些网页中的段落文字、列表、表格等信息。联想到HTML的DOM树结构,就想是不是用XPath来解析会比较合适。于是自己想从Python结合XPath的方向入手来实现网页内容解析。提到Python与XPath结合,就要用到lxml这个包了。它是一款由StefanBehnel等开发者......
  • 软件测试|深入理解SQL RIGHT JOIN:语法、用法及示例解析
    引言在SQL中,JOIN是一种重要的操作,用于将两个或多个表中的数据关联在一起。SQL提供了多种JOIN类型,其中之一是RIGHTJOIN。RIGHTJOIN用于从右表中选择所有记录,并将其与左表中匹配的记录组合在一起。本文将深入探讨SQLRIGHTJOIN的语法、用法以及通过实例解析来说明其作用。RIGH......
  • 软件测试|深入理解SQL FULL JOIN:语法、用法及示例解析
    简介在SQL中,JOIN是一个强大的操作,它允许将两个或多个表中的数据进行关联。SQL提供了多种JOIN类型,其中之一是FULLJOIN。FULLJOIN允许从左表和右表中选择所有记录,并将它们组合在一起。本文将深入探讨SQLFULLJOIN的语法、用法,并通过实例解析来说明其作用。FULLJOIN基本语法......
  • ImportError: cannot import name 'parse_xml' from 'docx.oxml'
    问题解决:查看每一个报错的文件,比如__init__.py, composer.py找到报错的这一行,比如:fromdocx.oxmlimportparse_xml替换为:fromdocx.oxml.parserimportparse_xml注意:可能有多个文件出现这个问题,需要逐一解决!......
  • 【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到Use
    问题描述示例调用MSGraphSDK通过Userprincipalname获取到User信息,如ObjectID。 参考资料选择MicrosoftGraph身份验证提供程序: https://learn.microsoft.com/zh-cn/graph/sdks/choose-authentication-providers?tabs=java#using-a-client-secret-2MicrosoftGraphSDKfor......
  • 强制等待和隐式等待示例
    背景知识 发送回车键  fromselenium.webdriver.common.keysimportKeysdriver.find_element(By.CSS_SELECTOR,loc).send_keys(Keys.ENTER)  隐式等待的意思是当符合条件就结束等待,不符合持续等待对比   第一种 强制等待fromseleniumimportwebdri......