如何将HTML插入Word?

问题描述 投票:0回答:1

我有一个用于获取文本的 HtmlEditor 。 (

第一段。

块引用中的段落。

第二段。

我想将 html 插入到 word 中。我使用 open xml 但不起作用。

void ConvertHTML(string htmlFileName, string docFileName)
{
    // Create a Wordprocessing document. 
    using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document))
    {
        // Add a new main document part. 
        package.AddMainDocumentPart();

        // Create the Document DOM. 
        package.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(new Body());
        Body body = package.MainDocumentPart.Document.Body;

        XPathDocument htmlDoc = new XPathDocument(htmlFileName);

        XPathNavigator navigator = htmlDoc.CreateNavigator();
        XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable);
        mngr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

        XPathNodeIterator ni = navigator.Select("html");
        while (ni.MoveNext())
        {
            body.AppendChild<Paragraph>(new Paragraph(new Run(new  Text(ni.Current.Value))));
        }

        // Save changes to the main document part. 
        package.MainDocumentPart.Document.Save();
    }
}

编辑

这个链接链接非常有用

c# asp.net sharepoint sharepoint-2010
1个回答
0
投票
public static void ConvertHTML(string htmlFilePath, string wordFilePath)
{
    //Read HTML file content
    string HTML = File.ReadAllText(htmlFilePath);

    using WordprocessingDocument wordDocument = WordprocessingDocument.Create(wordFilePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

    // Add a new main document part. 
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    
    mainPart.Document = new Document();
    Body body = new();
    mainPart.Document.Append(body);

    //Write HTML content
    Paragraph paragraph = new();
    Run run = new();
    run.Append(new Text(HTML));
    paragraph.Append(run);
    body.Append(paragraph);

    //Save the document
    mainPart.Document.Save();

}
© www.soinside.com 2019 - 2024. All rights reserved.