1

我正在使用 Microsoft 图形 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");

我究竟做错了什么?

4

1 回答 1

0

如本答案中所述,您需要调用PutXDocument()方法MainDocumentPart才能成功反映您的更改,因为目前,您正在进行更改但未将它们提交到所需的文档。

于 2020-09-24T06:00:48.907 回答