首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用OpenXML从HTML文件中生成docx文件

用OpenXML从HTML文件中生成docx文件
EN

Stack Overflow用户
提问于 2016-05-11 14:20:06
回答 3查看 15K关注 0票数 5

我使用这个方法来生成docx文件:

代码语言:javascript
复制
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);
        }
    }
}

它的作用就像一个护身符:

代码语言:javascript
复制
CreateDocument("test.docx", "Hello");

但是,如果我想放置超文本标记语言内容而不是Hello,该怎么办?例如:

代码语言:javascript
复制
CreateDocument("test.docx", @"<html><head></head>
                              <body>
                                    <h1>Hello</h1>
                              </body>
                        </html>");

或者类似这样的东西:

代码语言:javascript
复制
CreateDocument("test.docx", @"Hello<BR>
                                    This is a simple text<BR>
                                    Third paragraph<BR>
                                    Sign
                        ");

这两种情况都为document.xml创建了无效的结构。有什么想法吗?如何从HTML内容生成docx文件?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-05-11 14:44:26

您不能简单地将HTML内容插入到"document.xml“中,这部分只需要一个WordprocessingML内容,所以您必须将该HTML转换为WordprocessingML,see this

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

最后,作为另一种选择,使用GemBox.Document library可以完全实现您想要的功能,请参见以下内容:

代码语言:javascript
复制
public static void CreateDocument(string documentFileName, string text)
{
    DocumentModel document = new DocumentModel();
    document.Content.LoadText(text, LoadOptions.HtmlDefault);
    document.Save(documentFileName);
}

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

代码语言:javascript
复制
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);
}
票数 6
EN

Stack Overflow用户

发布于 2018-07-06 07:45:51

我意识到我已经晚了7年了。尽管如此,对于未来寻找如何从超文本标记语言转换为Word文档的人来说,Microsoft MSDN网站上的this博客文章给出了使用OpenXML实现这一转换所需的大部分要素。我发现这篇文章本身是令人困惑的,但他所包含的source代码为我澄清了一切。

唯一缺少的部分是如何从头开始构建Docx文件,而不是如何合并到现有的Docx文件中,如他的示例所示。我从here上发现了这条消息。

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

vb.net代码:

代码语言:javascript
复制
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#代码:

代码语言:javascript
复制
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内存流,该例程在使用后将其丢弃。

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

票数 10
EN

Stack Overflow用户

发布于 2020-12-17 23:08:06

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

代码语言:javascript
复制
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();
}

保存在磁盘上的步骤

代码语言:javascript
复制
System.IO.File.WriteAllBytes("filename.docx", generatedDocument.ToArray());

若要在net core mvc中返回要下载的文件,请使用

代码语言:javascript
复制
return File(generatedDocument.ToArray(), 
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "filename.docx");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37154495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档