我目前正在将对象导出到 .xlsx 文件中。这与我需要的非常接近,在 ASP.NET Core 中导出 xlsx ,但问题是 - 这是导出到本地项目文件夹 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。