将HTML插入OpenXML Word文档(.Net)

Nic*_*ico 7 .net word-2007 openxml

使用OpenXML SDK,我想将基本HTML片段插入到Word文档中.

你会怎么做:

  • 直接操作XML?
  • 使用XSLT?
  • 使用AltChunk?

而且,C#或VB的例子非常受欢迎:)

Rik*_*iko 6

这是另一种(相对较新的)替代方案

http://notesforhtml2openxml.codeplex.com/


Dir*_*mar 5

好吧,很难给出一般性建议,因为这在很大程度上取决于您的输入什么是最好的。

下面是使用 OpenXML SDK v2.0 和 XPathDocument 为 (X)HTML 文档中的每个段落插入一个段落到 DOCX 文档的简单示例:

    void ConvertHTML(string htmlFileName, string docFileName)
    {
        // Create a Wordprocessing document. 
        using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document))
        {
            // Add a new main document part. 
            package.AddMainDocumentPart();

            // Create the Document DOM. 
            package.MainDocumentPart.Document = new Document(new Body());
            Body body = package.MainDocumentPart.Document.Body;

            XPathDocument htmlDoc = new XPathDocument(htmlFileName);

            XPathNavigator navigator = htmlDoc.CreateNavigator();
            XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable);
            mngr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

            XPathNodeIterator ni = navigator.Select("//xhtml:p", mngr);
            while (ni.MoveNext())
            {
                body.AppendChild<Paragraph>(new Paragraph(new Run(new Text(ni.Current.Value))));
            }

            // Save changes to the main document part. 
            package.MainDocumentPart.Document.Save();
        }
    }
Run Code Online (Sandbox Code Playgroud)

该示例要求您的输入是有效的 XML,否则在创建 XPathDocument 时会出现异常。

请注意,这是一个非常基本的示例,没有考虑任何格式、标题、列表等。


Gas*_*agy 2

我不确定您实际上想要实现什么。OpenXML 文档对于格式元素(如段落、粗体文本等)有自己的类似 html (WordprocessingML) 表示法。如果您想使用基本格式向文档添加一些文本,我宁愿建议使用 OpenXML 语法并用它来格式化插入的文本。

如果您有一个 html 片段,必须将其原样包含到文档中,则可以使用 OpenXML 的“外部内容”功能。对于外部内容,您可以将 HTML 文档包含到包中,并在文档中要包含此内容的位置中创建引用 (altChunk)。此解决方案的缺点是,并非所有工具都支持(或正确支持)生成的文档,因此我不推荐此解决方案,除非您确实无法更改 HTML 源。

恕我直言,如何将任何内容(wordml)包含到 openxml word 文档中是一个独立的问题,答案很大程度上取决于您想要应用的修改的复杂程度以及文档有多大。对于一个简单的文档,我只需从包中读出文档部分,获取它的流并将其加载到 XmlDocument 中。您可以轻松地将其他内容插入到 XmlDocument 中,然后将其保存回包中。如果文档很大,或者需要在多个地方进行复杂的修改,XSLT 是一个不错的选择。

  • 你是对的,但我正在寻找经验的回报。到目前为止,我已经实现了altChunk,但它仅在您有Word2007(而不是兼容包)时才有效。 (2认同)