【问题标题】:Converting HTML to Word Docx with style intact将 HTML 转换为 Word Docx,样式保持不变
【发布时间】:2017-07-16 10:07:58
【问题描述】:

我知道已经有类似的问题了,建议Open XML之类的。

我正在使用 Open XMl,但它只适用于内联样式。

是否有任何解决方案,或任何其他更好的方式将 html 转换为 docx,而不是 Open XML。

谢谢!

【问题讨论】:

    标签: c# openxml


    【解决方案1】:

    您可以使用here 中描述的工具来内联 CSS 文件。

    然后,执行转换(改编自Eric White's blog):

    using (WordprocessingDocument myDoc =
        WordprocessingDocument.Open("ConvertedDocument.docx", true))
    {
        string altChunkId = "AltChunkId1";
        MainDocumentPart mainPart = myDoc.MainDocumentPart;
        var chunk = mainPart.AddAlternativeFormatImportPart(
            AlternativeFormatImportPartType.Html, altChunkId);
    
        using (FileStream fileStream = File.Open("YourHtmlDocument.html", FileMode.Open))
        {
            chunk.FeedData(fileStream);
        }
        AltChunk altChunk = new AltChunk() {Id = altChunkId};
    
        mainPart.Document.Body.InsertAfter(
                   altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
        mainPart.Document.Save();
    }
    

    这并不是将 HTML 完全转换为 DOCX。它将YourHtmlDocument.html 附加到ConvertedDocument.docx。如果ConvertedDocument.docx 最初为空,则此方法实际上是一种转换。

    每当您使用AltChunk 构建文档时,您的 HTML 都会嵌入到文档中,直到下次在 Word 中打开该文档。此时,HTML 将转换为 WordProcessingML 标记。如果文档无法在 MS Word 中打开,这实际上只是一个问题。如果您要上传到 Google 文档、在 OpenOffice 中打开或使用 COM 转换为 PDF,那么 OpenXML 就不够用了。在这种情况下,您可能需要使用像 Aspose.Words 这样的付费工具。

    【讨论】:

    • 如果之前没有插入任何段落,则会在 Elements&lt;Paragraph&gt;().Last() 上崩溃,因为无法找到 Last()。请改用mainPart.Document.Body.InsertAfterSelf(altChunk);
    • 如何在word文档的页眉页脚中插入altchunk?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2015-06-11
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多