我有一个pptx模板文件。我将文件加载到内存中,并使用openxml将pptx文件中的占位符替换为从数据库中获取的数据,然后下载该文件。这是我所做的,但这并没有下载它尝试一段时间的文件,然后显示“失败-网络错误”。
[HttpGet]
public async Task<IActionResult> Generate()
{
IDictionary<string, string> toReplace = new Dictionary<string, string>();
toReplace.Add("Sample2", "Sample - Text!");
toReplace.Add("Sample3", "Sample 3 - Text!");
var filePath = @"C:\Users\TestUser\Downloads\TestFile.pptx";
using (var templateFile = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var memoryStream = new MemoryStream())
{
templateFile.CopyTo(memoryStream);
using (PresentationDocument presentationDocument = PresentationDocument.Open(memoryStream, true))
{
// Get the presentation part of the presentation document.
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation part and presentation exist.
if (presentationPart != null && presentationPart.Presentation != null)
{
// Get the Presentation object from the presentation part.
Presentation presentation = presentationPart.Presentation;
// Verify that the slide ID list exists.
if (presentation.SlideIdList != null)
{
foreach (var slideId in presentation.SlideIdList.Elements<SlideId>())
{
SlidePart slidePart = presentationPart.GetPartById(slideId.RelationshipId) as SlidePart;
ShapeTree tree = slidePart.Slide.CommonSlideData.ShapeTree;
foreach (DocumentFormat.OpenXml.Presentation.Shape shape in tree.Elements<DocumentFormat.OpenXml.Presentation.Shape>())
{
// Run through all the paragraphs in the document
foreach (Paragraph paragraph in shape.Descendants().OfType<Paragraph>())
{
foreach (Run run in paragraph.Elements<Run>())
{
foreach (var kvp in toReplace)
{
if (run.Text.InnerText.Contains(kvp.Key))
{
run.Text = new DocumentFormat.OpenXml.Drawing.Text(kvp.Value);
}
}
}
}
}
}
}
}
//presentationPart.Presentation.Save();
}
memoryStream.Seek(0, SeekOrigin.Begin);//scroll to stream start point
MemoryStream memstr = new MemoryStream
{
Position = 0
};
memoryStream.CopyTo(memstr);
return File(memstr, System.Net.Mime.MediaTypeNames.Application.Octet, System.IO.Path.GetFileName(filePath));
}
}
}
您在using块外使用memoryStream
。尝试将其移到内部
using (var memoryStream = new MemoryStream())
{
...
memoryStream.Seek(0, SeekOrigin.Begin);//scroll to stream start point
MemoryStream memstr = new MemoryStream
{
Position = 0
};
memoryStream.CopyTo(memstr);
return File(memstr, System.Net.Mime.MediaTypeNames.Application.Octet, System.IO.Path.GetFileName(filePath));
}
您实际上不需要在这里创建另一个MemoryStream对象