这是我想要完成的。
我正在创建一个 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);
我已经搜索并尝试了多种不同的变体,但是当应用程序遇到 return File() 时,它返回 null。
我已经逐步执行,结果似乎在那里,但它没有通过任何东西。任何关于这里有什么问题的帮助将不胜感激。