我可以重现该错误“……内容有问题”通过使用
不完整的 HTML 文档作为替代格式导入部分的内容。
例如,如果您使用以下 HTML 片段<h1>HELLO</h1>
MS Word 无法打开该文档。
下面的代码展示了如何添加AlternativeFormatImportPart
到一个word文档。
(我已经使用 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
到身体元素。
欲了解更多信息w:altChunk
元素看这个MSDN http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.altchunk.aspx link.
EDIT
正如 @user2945722 所指出的,为了确保 OpenXml 库正确地将字节数组解释为 UTF-8,您应该添加 UTF-8 前导码。这可以通过以下方式完成:
MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(htmlEncodedString)).ToArray()
这将防止您的 é 被渲染为 é、您的 ä 被渲染为 ¤ 等。