这是 ASP.Net Core 7.0 和 Open XML SDK 2.19.0.
我正在将现有模板 Word 文档从磁盘克隆到新文件,然后使用 AltChunk 在占位符文本指示的特定位置插入 HTML。无论 AltChunk 中的内容多么简单,当我尝试在 Word 中打开它时,文档总是报告为已损坏。
string rootPath = _environment.WebRootPath;
string filePath = Path.Combine(rootPath, "files", "quotes", $"{DetailedQuote.Quote.QuoteID}.docx");
// Open the original template document and clone it to the new path as editable
DetailedTemplate.templateDocument = (WordprocessingDocument) _document.ReadWordDoc(quote.Template.TemplateID, "template").Clone(filePath, true);
// Insert content from service documents
var mainPart = DetailedTemplate.templateDocument.MainDocumentPart;
var paragraphs = mainPart.Document.Body.Descendants<Paragraph>();
foreach (var paragraph in paragraphs)
{
if (paragraph.InnerText == "[##(SERVICE_DETAILS)##]")
{
string serviceDescriptionHTML = "Hello";
var chunkID = 0;
foreach (var service in DetailedQuote.Quote.QuoteServices)
{
string sChunkID = $"myhtmlID{chunkID++}";
AlternativeFormatImportPart oChunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, sChunkID);
using(MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(serviceDescriptionHTML)))
{
oChunk.FeedData(memoryStream);
}
AltChunk oAltChunk = new AltChunk();
oAltChunk.Id =sChunkID ;
// Add the chunk to the paragraph
paragraph.Parent.InsertAfter(oAltChunk, paragraph);
}
}
}
// Save changes to the main document
mainPart.Document.Save();
// Close the document so that we can read it from disk
DetailedTemplate.templateDocument.Close();
// Return the content of the main document as a FileResult
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "MyDocument.docx");
我在创建文档后运行的 OpenXmlValidator(未包含在我的示例中)没有报告任何错误,Open XML SDK 2.5 生产力工具也没有。
如果我只是更新段落的文本,则文档在 Word 中打开时不会出现错误。
...
foreach (var service in DetailedQuote.Quote.QuoteServices)
{
var text = paragraph.Descendants<Text>().FirstOrDefault();
if (text != null)
{
text.Text = "This is text!";
}
}
...
这对我来说只能意味着添加 AltChunk 会搞砸,但据我所知,添加 AltChunk 是将 HTML 添加到 Word 文档的正确方法。
我花了两天时间阅读了我能找到的关于该主题的几乎所有内容,我已经请那里的每个机器人帮助我找到问题,我已经尝试过 Open-Xml-PowerTools 但找不到任何好的文档,我已经尝试过 HtmlToOpenXml 但遇到了版本控制问题,并且我已经打开 .docx 文件以手动挖掘它但到目前为止还无法解决这个问题。
非常感谢任何帮助!
[编辑]
如果我允许 Word 尝试打开生成的文档,内容就会出现并且看起来像预期的那样。如果我随后将“恢复的”文档另存为新文件,如果我再次使用 Word 打开它,该文档也将被标记为已损坏。
出现问题是因为Microsoft Word无法将“Hello”解析为HTML,是的...我知道...
无论如何,尝试使用这个:
string serviceDescriptionHTML = "<html>Hello</html>";
或者这个:
string serviceDescriptionHTML = "<body>Hello</body>";
或者这个:
string serviceDescriptionHTML = "<!DOCTYPE html>Hello";