我正在使用这种方法来生成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文件?
您不能仅将HTML内容插入“ document.xml”中,这部分仅需要WordprocessingML内容,因此您必须将该HTML转换为WordprocessingML,请参见this。
您可以使用的另一件事是altChunk元素,通过它您可以将HTML文件放置在DOCX文件中,然后将该HTML内容引用到文档中某个特定的位置,请参见this。
最后,作为替代方案,使用GemBox.Document库可以完全完成所需的操作,请参见以下内容:
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句