Добавить строку с тегами HTML, чтобы открыть слово XML - PullRequest
0 голосов
/ 09 мая 2019

Я пытаюсь добавить текст в формате html в текст Open xml. Как я могу применить форматирование, уже присутствующее в тексте?

Я применяю текст следующим образом:

TextElement.Text = formattedString;

где FormattedString содержит следующее:

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

На данный момент он просто вставляет текст с тегами в документ word. Как я могу сказать Open XML SDK добавить строку в правильном формате?

1 Ответ

0 голосов
/ 09 мая 2019

Вам нужно создать AlternativeFormatImportPart, который содержит ваш HTML, затем вам нужно добавить AltChunk к вашему документу и присвоить ему id из AlternativeFormatImportPart.

Следующий код создает файл с нуля с вашим HTML-кодом.Обратите внимание, что фрагменты HTML не поддерживаются, поэтому я добавил теги <html> в ваш HTML-фрагмент.

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();
}

Это приведет к следующему выводу:

enter image description here

...