1

Is it possible to insert a HTML fragment into a TableCell for a WordProcessingDocument created using OpenXML?

For example, when I use:

public void WriteWordFile()
{
    var fileName = HttpContext.Current.Request.PhysicalApplicationPath + "/temp/" + HttpContext.Current.Session.SessionID + ".docx";
    using (var wordDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document, true))
    {
        var mainPart = wordDocument.AddMainDocumentPart();
        mainPart.Document = new Document();
        var body = mainPart.Document.AppendChild(new Body());
        var table = new Table();
        var tr = new TableRow();
        var tc = new TableCell();
        tc.Append(new Paragraph(new Run(new Text("1"))));
        tr.Append(tc);
        table.Append(tr);
        body.Append(table);
    }

the Word document prints a simple "1" with no formatting as expected.

However, what I want to do is write:

public void WriteWordFile()
{
    var fileName = HttpContext.Current.Request.PhysicalApplicationPath + "/temp/" + HttpContext.Current.Session.SessionID + ".docx";
    using (var wordDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document, true))
    {
        var mainPart = wordDocument.AddMainDocumentPart();
        mainPart.Document = new Document();
        var body = mainPart.Document.AppendChild(new Body());
        var table = new Table();
        var tr = new TableRow();
        var tc = new TableCell();
        tc.Append(new Paragraph(new Run(new Text("<span style=\"bold\">1</span>"))));
        tr.Append(tc);
        table.Append(tr);
        body.Append(table);
    }
}

The Word document prints the HTML markup "<span style="bold">1</span>" instead of a bold "1".

kyletme
  • 441
  • 4
  • 17

1 Answers1

1

No, Word does not support what is described in the question.

HTML is not Word's native format - a converter is required to incorporate HTML into Word content.

In the UI, this is accomplished via pasting or inserting from a file.

In Open XML it's possible to use the altChunk method to "embed" content in a foreign format in the document package. When Word opens the document and encounters an altChunk it invokes the appropriate converter to turn it into native Word content (Word Open XML); during the process, the original embedded content is removed. There's no guarantee, however, that the result will be what a native environment (in the case of HTML a browser) returns.

Searching "altChunk" should turn up numerous discussions, blog articles, etc.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
  • Thanks Cindy. I have seen examples of the atlChunk method. I am just trying to figure out how to export fragments of HTML content, created using an HTML text editor control, to a structured Word document. – kyletme Mar 10 '20 at 22:26