首页 > 解决方案 > Word 在打开文件时发现无法读取的内容错误

问题描述

我在打开 Word (.docx) 文件时遇到错误“ Word 在 abc.docx 中发现不可读的内容。您要恢复此文档的内容吗? ”。

我已经尝试过互联网上给出的所有解决方案,但没有成功。下面是我将内容写入流的代码。

private void test()
        {
            using (MemoryStream one = await db.DownloadFile("templates", "one.docx"))
            {
                using (MemoryStream two = await db.DownloadFile("templates", "two.docx"))
                {
                    using (MemoryStream newStream = new MemoryStream())
                    {
                        one.CopyTo(newStream);
                        editingMemoryStream.Position = 0;

                        using (WordprocessingDocument mainDoc = WordprocessingDocument.Open(one, true))
                        {
                            using (WordprocessingDocument newDoc =
                                WordprocessingDocument.Open(newStream, true))
                            {
                                Generate(modal, new, main, report);
                            }
                        }
                    }
                }
            }
        }
private void Generate(List<modal> mo, WordprocessingDocument new, MemoryStream report)
 {
     var main = new.MainDocumentPart;
     modal = mo[0];

     AddTableToBody(report, modal.table, mo);        
  }

public void AddTableToBody(MemoryStream temp, dailyReport,
                    MainDocumentPart main)
   {
            using (WordprocessingDocument newDoc = WordprocessingDocument.Open(editingMemoryStream, true))
            {
                WP.Body body= dailyReport.MainDocumentPart.Document.Body;
                var main = dailyReport.MainDocumentPart;
                //* some code is here*//

                var clone = dailyReport.CloneNode(true);
                main.Document.Body.AppendChild(new WP.Paragraph(new WP.Run(clone)));
                main.Document.Save();
            }
        }

该文件包含 2 个带有一些标签的表格。

标签: c#openxmlasp.net-core-2.1openxml-sdkmemorystream

解决方案


查看您的代码,您似乎在以下两行代码中将元素(实例)添加到元素(实例w:bodyBodyw:rRun

var clone = dailyReport.CloneNode(true);
main.Document.Body.AppendChild(new WP.Paragraph(new WP.Run(clone)));

在上面的摘录中,clone是一个Body实例(w:body元素)及其所有子元素。我只能假设parentMainDocumentPart其他的WordprocessingDocument。您正在附加一个带有一个 ( ) 的新( ) 和一个( ) 以及Paragraph后者具有的任何子级。这是无效的 Open XML,很可能是 Word 抱怨的原因。w:pw:rRunw:bodyBody


推荐阅读