c# - 使用 OpenXML 从 HTML 文件生成 docx 文件

标签 c# openxml docx sql-server-openxml

我正在使用此方法生成 docx 文件:

public static void CreateDocument(string documentFileName, string text)
{
    using (WordprocessingDocument wordDoc =
        WordprocessingDocument.Create(documentFileName, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

        string docXml =
                    @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
                 <w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
                 <w:body><w:p><w:r><w:t>#REPLACE#</w:t></w:r></w:p></w:body>
                 </w:document>";

        docXml = docXml.Replace("#REPLACE#", text);

        using (Stream stream = mainPart.GetStream())
        {
            byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
            stream.Write(buf, 0, buf.Length);
        }
    }
}

它就像一个魅力:

CreateDocument("test.docx", "Hello");

但是如果我想放置 HTML 内容而不是 Hello 怎么办?例如:

CreateDocument("test.docx", @"<html><head></head>
                              <body>
                                    <h1>Hello</h1>
                              </body>
                        </html>");

或者像这样:

CreateDocument("test.docx", @"Hello<BR>
                                    This is a simple text<BR>
                                    Third paragraph<BR>
                                    Sign
                        ");

这两种情况都会为 document.xml 创建一个无效的结构。 任何想法?如何从 HTML 内容生成 docx 文件?

最佳答案

我意识到我迟到了 7 年。尽管如此,对于 future 搜索如何从 HTML 转换为 Word Doc 的人来说,this Microsoft MSDN 站点上的博客文章提供了使用 OpenXML 执行此操作所需的大部分要素。我发现帖子本身令人困惑,但是 source他包含的代码为我澄清了这一切。

唯一缺少的部分是如何从头开始构建 Docx 文件,而不是如他的示例所示如何合并到现有文件中。我从 here 找到了那个花絮.

不幸的是,我使用它的项目是用 vb.net 编写的。所以我将首先分享 vb.net 代码,然后是它的自动 C# 转换,这可能准确也可能不准确。

vb.net 代码:

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports System.IO

Dim ms As IO.MemoryStream
Dim mainPart As MainDocumentPart
Dim b As Body
Dim d As Document
Dim chunk As AlternativeFormatImportPart
Dim altChunk As AltChunk

Const altChunkID As String = "AltChunkId1"

ms = New MemoryStream()

Using myDoc = WordprocessingDocument.Create(ms,WordprocessingDocumentType.Document)
    mainPart = myDoc.MainDocumentPart

    If mainPart Is Nothing Then
        mainPart = myDoc.AddMainDocumentPart()

        b = New Body()
        d = New Document(b)
        d.Save(mainPart)
    End If

    chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkID)

    Using chunkStream As Stream = chunk.GetStream(FileMode.Create, FileAccess.Write)
        Using stringStream As StreamWriter = New StreamWriter(chunkStream)
            stringStream.Write("YOUR HTML HERE")
        End Using
    End Using

    altChunk = New AltChunk()
    altChunk.Id = altChunkID
    mainPart.Document.Body.InsertAt(Of AltChunk)(altChunk, 0)
    mainPart.Document.Save()
End Using

C#代码:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

IO.MemoryStream ms;
MainDocumentPart mainPart;
Body b;
Document d;
AlternativeFormatImportPart chunk;
AltChunk altChunk;

string altChunkID = "AltChunkId1";

ms = new MemoryStream();

Using (myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
    mainPart = myDoc.MainDocumentPart;

    if (mainPart == null) 
    {
         mainPart = myDoc.AddMainDocumentPart();
         b = new Body();
         d = new Document(b);
         d.Save(mainPart);
    }

    chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkID);

    Using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write)
    {
         Using (StreamWriter stringStream = new StreamWriter(chunkStream))         
         {
              stringStream.Write("YOUR HTML HERE");
         }
    }    

    altChunk = new AltChunk();
    altChunk.Id = altChunkID;
    mainPart.Document.Body.InsertAt(Of, AltChunk)[altChunk, 0];
    mainPart.Document.Save();
}

请注意,我在另一个例程中使用了 ms 内存流,这是它在使用后被丢弃的地方。

我希望这对其他人有帮助!

关于c# - 使用 OpenXML 从 HTML 文件生成 docx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37154495/

相关文章:

java - 使用 Docx4j 将 DOCX 转换为 PDF 时保留字体

java - 如何在 DOCX4J 中保存 word 文档中的图像

java - Docx4j 如何解释 css

c# - 给定矩形的 4 个点,忽略这 4 个点,是否有任何边相交?

c# - SQL 连接

c# - 将 Open XML Excel 文件转换为 HTML

sql - 通过 OpenXML 解析具有多个父节点和多个子节点的 XML

c# - 我在 C# 中有一个 2d (n x n) 字符串数组,如何将它动态地输出到网页(尝试过数据表/绑定(bind)等...)

c# - 生命周期范围由 IoC 容器处理的单元测试对象

c# - 如何使用 C# 和 OpenXML 在 PowerPoint 演示文稿中调整大小和图像