首页 > 解决方案 > c# OpenXML WordprocessingDocumentType 在 TableCell 中插入 HTML 片段

问题描述

是否可以为使用 OpenXML 创建的 WordProcessingDocument 将 HTML 片段插入 TableCell 中?

例如,当我使用:

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

Word 文档打印一个简单的“1”,没有按预期进行格式化。

但是,我想做的是写:

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

Word 文档打印 HTML 标记“ <span style="bold">1</span>”而不是粗体“ 1 ”。

标签: c#htmlms-wordopenxml

解决方案


不,Word 不支持问题中描述的内容。

HTML 不是 Word 的本机格式 - 需要转换器才能将 HTML 合并到 Word 内容中。

在 UI 中,这是通过从文件中粘贴或插入来完成的。

在 Open XML 中,可以使用该altChunk方法在文档包中以外部格式“嵌入”内容。当 Word 打开文档并遇到altChunk它时,它会调用适当的转换器将其转换为原生 Word 内容(Word Open XML);在此过程中,原始嵌入内容被删除。但是,无法保证结果将是本机环境(在 HTML 的情况下为浏览器)返回的结果。

搜索“altChunk”应该会出现大量讨论、博客文章等。


推荐阅读