修改后的Word文档未保存在内存流中

问题描述

我正在使用Microsoft graph API作为流从SharePoint获取Word文档,并更改了该文件中的某些内容,然后将保存的内容下载为文件,但是当我打开文件时,修改后的内容不可用。下载的文件仍然显示原始内容

       using (var memoryStream = new MemoryStream())
         {
            templateStream.Position = 0;
            // copying the stream that I've got into memory stream
            await templateStream.copyToAsync(memoryStream).ConfigureAwait(false);
            memoryStream.Position = 0;

            using (var wordDocument = WordprocessingDocument.Open(memoryStream,true))
            {
                RevisionAccepter.AcceptRevisions(wordDocument);
                var document = wordDocument.MainDocumentPart.GetXDocument();
                var content = document.Descendants(W.p).ToList();
                //based on the dictionary I've I am replacing the contents of the file
                foreach (var field in dataDictionary)
                {
                    var regex = new Regex(field.Key,RegexOptions.IgnoreCase);
                    OpenXmlRegex.Replace(content,regex,field.Value.ToString(),null);
                }
                //not showing the modified content
                wordDocument.Save();
                //this is also not updating the memorystream variable with the modified content
                wordDocument.MainDocumentPart.Document.Save();
                memoryStream.Position = 0;
                await memoryStream.FlushAsync().ConfigureAwait(false);
            }

            var result = memoryStream.ToArray();
            memoryStream.Flush();
            return result;
        }

一旦我从上面的代码中获得了字节数组,我就从控制器使用这一行下载了文件

  return File(returnResponse,System.Net.Mime.MediaTypeNames.Application.Octet,$"Test- 
               {System.DateTime.Now}.docx");

我在做什么错了?

解决方法

如本answer所述,您需要在MainDocumentPart上调用PutXDocument()方法,以使更改成功反映出来,因为当前您是在进行更改,而不是将其提交给所需文件。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...