问题描述
我正在使用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()方法,以使更改成功反映出来,因为当前您是在进行更改,而不是将其提交给所需文件。