【问题标题】:Add String with html tags to open xml word添加带有 html 标签的字符串以打开 xml 单词
【发布时间】:2019-05-09 14:26:26
【问题描述】:

我正在尝试将 html 格式的文本添加到 Open xml 文本中。 如何应用文本中已经存在的格式?

我将文本应用如下:

TextElement.Text = formattedString;

其中 FormattedString 包含以下内容:

<p>test<br/>test2<ul><li>item1</li><li>item2<li2></p>

目前,它只是将带有标签的文本原样插入到 word 文档中。 如何告诉 Open XML SDK 添加格式正确的字符串?

【问题讨论】:

标签: c# html openxml openxml-sdk


【解决方案1】:

您需要创建一个包含您的 HTML 的AlternativeFormatImportPart,然后您需要将一个AltChunk 添加到您的文档中,并将id 指定为AlternativeFormatImportPart

以下代码从头开始创建一个文件,其中包含您的 HTML。请注意,似乎不支持 HTML 片段,因此我在您的 HTML sn-p 中添加了 &lt;html&gt; 标记。

using (var document = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document))
{
    document.AddMainDocumentPart();
    document.MainDocumentPart.Document = new Document();
    document.MainDocumentPart.Document.Body = new Body();

    //create a memory stream with the HTML required
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><p>test<br/>test2<ul><li>item1</li><li>item2<li2></p><html>"));

    //Create an alternative format import part on the MainDocumentPart
    AlternativeFormatImportPart altformatImportPart = document.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html);

    //Add the HTML data into the alternative format import part
    altformatImportPart.FeedData(ms);

    //create a new altChunk and link it to the id of the AlternativeFormatImportPart
    AltChunk altChunk = new AltChunk();
    altChunk.Id = document.MainDocumentPart.GetIdOfPart(altformatImportPart);

    // add the altChunk to the document
    document.MainDocumentPart.Document.Body.Append(altChunk);

    document.Save();
}

这会产生以下输出:

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 2011-03-11
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多