c# 将html转化到word

c# 将html转化到word

1)HtmlToWordConverter.cs

cs 复制代码
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using HtmlAgilityPack;
using System.Collections.Generic;

namespace ConsoleApp9
{
    public class HtmlToWordConverter
    {
        public void ConvertHtmlToWord(List<string> bodyStrings, string titleString, string docxFilePath)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(docxFilePath, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());

                // Add centered title
                if (!string.IsNullOrEmpty(titleString))
                {
                    Paragraph titleParagraph = new Paragraph();
                    Run titleRun = new Run(new Text(titleString));
                    titleParagraph.AppendChild(new ParagraphProperties(new Justification() { Val = JustificationValues.Center }));
                    titleParagraph.Append(titleRun);
                    body.Append(titleParagraph);
                }

                // Convert each bodyString to Word content
                foreach (string bodyString in bodyStrings)
                {
                    HtmlDocument htmlDoc = new HtmlDocument();
                    htmlDoc.LoadHtml(bodyString);

                    ConvertHtmlNodesToWord(htmlDoc.DocumentNode.ChildNodes, body);
                }
            }
        }

        private void ConvertHtmlNodesToWord(HtmlNodeCollection nodes, OpenXmlElement parent)
        {
            foreach (HtmlNode node in nodes)
            {
                switch (node.Name)
                {
                    case "p": // Paragraph
                        Paragraph para = new Paragraph();
                        Run run = new Run();
                        ConvertHtmlToRun(node.ChildNodes, run);
                        para.Append(run);
                        parent.Append(para);
                        break;

                    case "h1": // Heading 1
                    case "h2": // Heading 2
                    case "h3": // Heading 3
                    case "h4": // Heading 4
                    case "h5": // Heading 5
                    case "h6": // Heading 6
                        Paragraph heading = new Paragraph();
                        Run runHeading = new Run();
                        RunProperties runPropHeading = new RunProperties();

                        // Set heading style based on HTML heading level
                        int headingLevel = int.Parse(node.Name.Substring(1)); // Extract the number from "h1" to "1"
                        if (headingLevel >= 1 && headingLevel <= 6)
                        {
                            runPropHeading.Append(new Bold());
                            runPropHeading.Append(new FontSize() { Val = new StringValue((24 - (headingLevel - 1) * 2).ToString()) });
                            runPropHeading.Append(new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "2E74B5" }); // You can adjust the color as needed
                        }
                        runHeading.Append(runPropHeading);
                        ConvertHtmlToRun(node.ChildNodes, runHeading);
                        heading.Append(runHeading);
                        parent.Append(heading);
                        break;

                    // Add more cases for other HTML elements like tables, lists, etc. as needed

                    default:
                        break;
                }

                if (node.HasChildNodes)
                {
                    ConvertHtmlNodesToWord(node.ChildNodes, parent);
                }
            }
        }

        private void ConvertHtmlToRun(HtmlNodeCollection nodes, Run run)
        {
            foreach (HtmlNode node in nodes)
            {
                switch (node.Name)
                {
                    case "#text": // Text node
                        run.AppendChild(new Text(node.InnerText));
                        break;

                    case "strong": // Strong (bold) text
                        RunProperties runPropStrong = new RunProperties(new Bold());
                        run.AppendChild(runPropStrong);
                        ConvertHtmlToRun(node.ChildNodes, run);
                        break;

                    case "em": // Emphasized (italic) text
                        RunProperties runPropEm = new RunProperties(new Italic());
                        run.AppendChild(runPropEm);
                        ConvertHtmlToRun(node.ChildNodes, run);
                        break;

                    // Add more cases for other HTML formatting elements as needed

                    default:
                        ConvertHtmlToRun(node.ChildNodes, run);
                        break;
                }
            }
        }
    }
}

2)Program.cs

cs 复制代码
using System;
using System.Collections.Generic;

namespace ConsoleApp9
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> bodyStrings = new List<string>{
            @"<h1>内容1</h1>
            <p>第一段内容</p>
            <p>第二段内容</p>",
            @"<h1>内容2</h1>
            <p>第一段内容</p>
            <p>第二段内容</p>"};

            string titleString = "HTML测试";
            string docxFilePath = AppDomain.CurrentDomain.BaseDirectory + "tests.docx";

            HtmlToWordConverter converter = new HtmlToWordConverter();
            converter.ConvertHtmlToWord(bodyStrings, titleString, docxFilePath);

            Console.WriteLine("生成word成功");
        }
    }
}
相关推荐
前端老鹰6 小时前
HTML <output> 标签:原生表单结果展示容器,自动关联输入值
前端·html
mudtools7 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
玩泥巴的8 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
word·二次开发·office·com互操作
芦苇Z10 小时前
HTML <a> 标签的 rel 属性全解析:安全、隐私与 SEO 最佳实践
前端·html
Alice-YUE13 小时前
【CSS学习笔记3】css特性
前端·css·笔记·html
大飞pkz13 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫15 小时前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
破无差1 天前
《赛事报名系统小程序》
小程序·html·uniapp
未来之窗软件服务1 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther1 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎