通过使用不完整的 HTML 文档作为替代格式导入部分的内容,我可以重现错误“...内容有问题” 。例如,如果您使用以下 HTML 片段,<h1>HELLO</h1>
MS Word 将无法打开该文档。
下面的代码显示了如何向AlternativeFormatImportPartword 文档添加一个。(我已经用 MS Word 2013 测试了代码)。
using (WordprocessingDocument doc = WordprocessingDocument.Open(@"test.docx", true))
{
string altChunkId = "myId";
MainDocumentPart mainDocPart = doc.MainDocumentPart;
var run = new Run(new Text("test"));
var p = new Paragraph(new ParagraphProperties(
new Justification() { Val = JustificationValues.Center }),
run);
var body = mainDocPart.Document.Body;
body.Append(p);
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body><h1>HELLO</h1></body></html>"));
// Uncomment the following line to create an invalid word document.
// MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));
// Create alternative format import part.
AlternativeFormatImportPart formatImportPart =
mainDocPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.Html, altChunkId);
//ms.Seek(0, SeekOrigin.Begin);
// Feed HTML data into format import part (chunk).
formatImportPart.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainDocPart.Document.Body.Append(altChunk);
}
根据 Office OpenXML 规范,元素的有效父元素
w:altChunk是body, comment, docPartBody, endnote, footnote, ftr, hdr and tc. 所以,我已将 加入w:altChunk到 body 元素中。
有关该w:altChunk元素的更多信息,请参阅此MSDN链接。
编辑
正如@user2945722 所指出的,要确保 OpenXml 库正确地将字节数组解释为 UTF-8,您应该添加 UTF-8 前导码。这可以通过以下方式完成:
MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(htmlEncodedString)).ToArray()
这将防止您的 é 被呈现为 é,您的 ä 被呈现为 ä 等。