使用Open XML SDK向Word文档添加AltChunk导致损坏求助
问题描述
环境:ASP.Net Core 7.0、Open XML SDK 2.19.0
从磁盘克隆现有Word模板到新文件后,尝试在占位符[##(SERVICE_DETAILS)##]所在段落位置,通过AltChunk插入HTML内容。无论HTML内容多简单,Word打开生成的文档时均提示损坏。允许Word尝试恢复后,内容显示正常;但保存“恢复后的文档”后,再次打开仍会被标记为损坏。
使用OpenXmlValidator与Open XML SDK 2.5生产力工具检查生成的文档,均未报告错误。若仅替换占位符段落的文本内容,文档可正常打开。
有问题的AltChunk插入代码
string rootPath = _environment.WebRootPath; string filePath = Path.Combine(rootPath, "files", "quotes", $"{DetailedQuote.Quote.QuoteID}.docx"); // 打开原始模板文档并克隆到新路径以编辑 DetailedTemplate.templateDocument = (WordprocessingDocument)_document.ReadWordDoc(quote.Template.TemplateID, "template").Clone(filePath, true); // 插入服务文档内容 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; // 将chunk添加到段落之后 paragraph.Parent.InsertAfter(oAltChunk, paragraph); } } } // 保存主文档更改 mainPart.Document.Save(); // 关闭文档以便从磁盘读取 DetailedTemplate.templateDocument.Close(); // 返回文档内容作为FileResult byte[] fileBytes = System.IO.File.ReadAllBytes(filePath); return File(fileBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "MyDocument.docx");
正常工作的文本替换代码
... foreach (var service in DetailedQuote.Quote.QuoteServices) { var text = paragraph.Descendants<Text>().FirstOrDefault(); if (text != null) { text.Text = "This is text!"; } } ...
内容的提问来源于stack exchange,提问作者Martin Edelius
相关产品推荐
相关产品推荐

