C# 在服务器上创建Excel文件并发送到浏览器
我正在使用EPPlus在服务器上创建excel文件。问题是,我不想将文件保存在客户端硬盘上,当我在服务器上启动应用程序时,我相信这会将文件保存在服务器硬盘上 是否可以通过某种方式将此文件发送回客户端/浏览器C# 在服务器上创建Excel文件并发送到浏览器,c#,asp.net-mvc,file,C#,Asp.net Mvc,File,我正在使用EPPlus在服务器上创建excel文件。问题是,我不想将文件保存在客户端硬盘上,当我在服务器上启动应用程序时,我相信这会将文件保存在服务器硬盘上 是否可以通过某种方式将此文件发送回客户端/浏览器 public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear) { List<Calculation> newList = new L
public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear)
{
List<Calculation> newList = new List<Calculation>();
newList.Add(cList.First()); //Getting the values for the first row
var StartValue = newList[0].StartValue;
var radio = form["advanceOrArrears"];
string fileName = newList[0].CalculationName;
string path = @"C:\ExcelFiles\" + fileName + ".xlsx"; //Path for the file
FileInfo info = new FileInfo(path);
info.Directory.Create(); //If C:\ExcelFiles does not exist, create it
if (!info.Exists)
{
using (ExcelPackage package = new ExcelPackage(info))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
//Styles for the sheet
package.Save();
}
}
}
public void CreateAnnuityExcelSheet(列表cList、表单集合表单、int DTCyear)
{
List newList=新列表();
newList.Add(cList.First());//获取第一行的值
var StartValue=newList[0]。StartValue;
var无线电=形式[“高级无线电”];
字符串文件名=新列表[0]。CalculationName;
字符串路径=@“C:\ExcelFiles\”+文件名+“.xlsx”;//文件的路径
FileInfo=newfileinfo(路径);
info.Directory.Create();//如果C:\ExcelFiles不存在,请创建它
如果(!info.Exists)
{
使用(ExcelPackage=新的ExcelPackage(信息))
{
Excel工作表ws=package.Workbook.Worksheets.Add(文件名);
//工作表的样式
package.Save();
}
}
}
我使用了httphandler将字节文件对象发送到浏览器
此链接应该会有所帮助,因此,请将文件保存在服务器上,然后将其传输给控制器中的用户:
return new FilePathResult(myFilePath,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
最简单的方法是将字节作为文件发送到浏览器。如果用于创建Excel文件的库允许您保存到流(例如,您可以这样做),那么您可以在MVC操作中这样做
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "file.xlsx");
如果无法将其保存到内存流,则将其保存到服务器的光盘,然后您可以将文件路径和内容类型传递到
return file()
,因此,保存到服务器的磁盘,完成后,将文件作为响应发送。我如何将其作为响应发送?我现在已经尝试了此操作,但无法工作。当我运行该方法时,什么也没有发生。我想要的是客户端获得下载的文件,但您正在从浏览器窗口运行此操作,是吗?“什么都没发生”是指浏览器中的白色屏幕吗?