如何解决Spire.xls - 从流中返回一个文件供客户端下载
这就是我想要完成的。
我正在创建一个 asp.net MVC 应用程序。我的限制是我无法以编程方式将任何内容保存到服务器的文件结构中,因此我无法将其保存为主机上的物理文件,然后将其抓取以供客户端下载。
我正在将 PDF 加载到流中,从 PDF 中提取信息,动态构建 Excel 文件,然后将该文件提供给客户端以供下载。我的代码如下。
// Loads the incoming PDF document to stream
PdfDocument doc = new PdfDocument();
using (var stream = model.BudgetPdfFile.OpenReadStream())
{
doc.LoadFromStream(stream);
}
var pageCount = doc.Pages.Count;
var date = DateTime.Now.ToShortDateString().Replace("/","-");
// Extracts data from the PDF and separates it by NewLine
SimpleTextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
StringBuilder allText = new StringBuilder();
for (var i = 0; i < pageCount; i++)
{
allText.Append(doc.Pages[i].ExtractText(strategy));
}
var fullDocText = allText.ToString();
List<string> linesList = new List<string>(fullDocText.Split(new[] { Environment.NewLine },StringSplitOptions.None).ToList());
// generates a comparison list for output data manipulation from static data
var finalList = linesList.BuildFinalList(budgetItems);
// creates a new Spire.PDF.Workbook for the final output excel file
var result = new Workbook();
// checks for whether the submitted budget is for a case in litigation or not and builds the correct excel workbook
if (model.isTrial)
{
result = ExportExcelBudget.TrialBudgetSheet(model,finalList);
}
else
{
result = ExportExcelBudget.PreTrialBudgetSheet(model,finalList);
}
绝对到下面最后一部分的所有内容都可以完美运行。但是,我无法弄清楚如何将工作簿加载到新流中,然后返回文件以供下载。
// saves the final workbook to a stream and offers it for download to the client
Stream outStream = new MemoryStream();
var fileName = "Budget Report_" + model.ClaimNumber + "_" + date + ".xlsx";
var contentType = "application/vnd.ms-excel";
result.SavetoStream(outStream,Spire.Xls.FileFormat.Version2016);
return File(outStream,contentType,fileName);
我已经搜索并尝试了多种不同的变体,但是当应用程序点击返回 File() 时,它返回一个空值。
我已经逐步执行,结果似乎就在那里,但它没有通过任何东西。任何有关此处错误的帮助将不胜感激。
解决方法
Stream outStream = new MemoryStream();
var fileName = "Budget Report_" + model.ClaimNumber + "_" + date + ".xlsx";
var contentType = "application/vnd.ms-excel";
result.SaveToStream(outStream,Spire.Xls.FileFormat.Version2016);
**outStream.Position = 0;**
return File(outStream,contentType,fileName);
必须将流位置重置为 0。现在工作完美。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。