我目前正在将对象导出到.xlsx文件中。这是我所需要的,Export xlsx in ASP.NET Core,但问题是 - 这是导出到本地项目文件夹wwwroot,我想导出到客户端机器。
我试过这个。
private readonly IHostingEnvironment _hostingEnvironment;
public ImportExportController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpGet]
[Route("Export")]
public FileStreamResult Export()
{
string sWebRootFolder = _hostingEnvironment.WebRootPath;
string sFileName = @"demo.xlsx";
string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
if (file.Exists)
{
file.Delete();
file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
}
using (ExcelPackage package = new ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
worksheet.Cells["C2"].Value = "M";
worksheet.Cells["D2"].Value = 5000;
worksheet.Cells["A3"].Value = 1001;
worksheet.Cells["B3"].Value = "Graham";
worksheet.Cells["C3"].Value = "M";
worksheet.Cells["D3"].Value = 10000;
worksheet.Cells["A4"].Value = 1002;
worksheet.Cells["B4"].Value = "Jenny";
worksheet.Cells["C4"].Value = "F";
worksheet.Cells["D4"].Value = 5000;
package.Save(); //Save the workbook.
}
FileStream RptStream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open, FileAccess.Read);
return new FileStreamResult(RptStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
但似乎我需要将工作表导出到wwwroot文件夹,然后再使用工作表URL返回filestreamresult。我不知道如何获取工作表的url传递filestreamresult函数。
有人可以帮帮我吗?我想在客户端计算机上导出此.xlsx而不是wwwroot。
尝试将文件写入内存流并让您的方法返回FileContentResult对象(通过Controller.File方法):
var stream = new MemoryStream(package.GetAsByteArray());
return File(stream.ToArray(), "application/vnd.ms-excel", sFileName);