代码之家  ›  专栏  ›  技术社区  ›  newbie

使用OpenXML从HTML文件生成docx文件

  •  5
  • newbie  · 技术社区  · 9 年前

    我正在使用此方法生成 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文件?

    3 回复  |  直到 9 年前
        1
  •  11
  •   Mmm Matt Johnson-Pint    7 年前

    我意识到我在这里比赛迟到了7年。不过,对于未来搜索如何从HTML转换为Word文档的人来说, 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 另一个例程中的内存流,使用后将在其中进行处理。

    我希望这能帮助别人!

        2
  •  6
  •   Mario Z    9 年前

    您不能只是将HTML内容插入到“document.xml”中,这部分只需要一个WordprocessingML内容,因此您必须将该HTML转换为WordproessingML, see this .

    您可以使用的另一个东西是altChunk元素,使用它,您可以将HTML文件放在DOCX文件中,然后在文档中的特定位置引用该HTML内容, see this .

    最后一个作为备选方案 GemBox.Document library 您完全可以完成您想要的,请参阅以下内容:

    public static void CreateDocument(string documentFileName, string text)
    {
        DocumentModel document = new DocumentModel();
        document.Content.LoadText(text, LoadOptions.HtmlDefault);
        document.Save(documentFileName);
    }
    

    或者您可以直接将HTML内容转换为DOCX文件:

    public static void Convert(string documentFileName, string htmlText)
    {
        HtmlLoadOptions options = LoadOptions.HtmlDefault;
        using (var htmlStream = new MemoryStream(options.Encoding.GetBytes(htmlText)))
            DocumentModel.Load(htmlStream, options)
                         .Save(documentFileName);
    }
    
        3
  •  2
  •   Bellash    4 年前

    使用以下代码,我可以在.net Core中使用OpenXML成功地将HTML内容转换为docx文件

    string html = "<strong>Hello</strong> World";
    using (MemoryStream generatedDocument = new MemoryStream()){
       using (WordprocessingDocument package = 
                      WordprocessingDocument.Create(generatedDocument,
                      WordprocessingDocumentType.Document)){
       MainDocumentPart mainPart = package.MainDocumentPart;
       if (mainPart == null){
        mainPart = package.AddMainDocumentPart();
        new Document(new Body()).Save(mainPart);
    }
    HtmlConverter converter = new HtmlConverter(mainPart);
    converter.ParseHtml(html);
    mainPart.Document.Save();
    }
    

    保存到磁盘

    System.IO.File.WriteAllBytes("filename.docx", generatedDocument.ToArray());
    

    要在net-coremvc中返回要下载的文件,请使用

    return File(generatedDocument.ToArray(), 
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
              "filename.docx");