c# – ASP.NET Core直接在一次调用服务器(动态)中返回excel文件(xlsx)?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – ASP.NET Core直接在一次调用服务器(动态)中返回excel文件(xlsx)?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2352字,纯文字阅读大概需要4分钟。
内容图文
![c# – ASP.NET Core直接在一次调用服务器(动态)中返回excel文件(xlsx)?](/upload/InfoBanner/zyjiaocheng/759/8c1fe5ea6c7144d9b7d4690059e7f839.jpg)
我找到了在服务器上生成excel文件(xlsx)的解决方案.首次调用它会删除文件demo.xlsx(如果存在)并生成新的demo.xlsx.
第一次打电话
http://localhost:8000/api/importexport/export
它生成excel文件(xlsx)并发送url进行下载
第二个电话
http://localhost:8000/demo.xlsx
下载文件.
在Configure方法的Startup类中,您必须添加
app.UseStaticFiles();
这是解决方案的链接
http://www.talkingdotnet.com/import-export-xlsx-asp-net-core/
这个解决方案的问题是我有两次调用服务器.
我想要一个电话
http://localhost:8000/api/importexport/export
直接下载excel文件(xlsx).
我听说可以在一次调用中下载excel文件(xlsx)而无需在服务器上创建文件(动态).
我很乐意在一次调用服务器时看到更好的解决方案.
解决方法:
这是我的解决方案
private readonly IHostingEnvironment _hostingEnvironment;
public ImportExportController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpGet]
[Route("Export")]
public IActionResult 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.
}
var result = PhysicalFile(Path.Combine(sWebRootFolder, sFileName), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
}.ToString();
return result;
}
如果有人有更好的解决方案,请发布.
内容总结
以上是互联网集市为您收集整理的c# – ASP.NET Core直接在一次调用服务器(动态)中返回excel文件(xlsx)?全部内容,希望文章能够帮你解决c# – ASP.NET Core直接在一次调用服务器(动态)中返回excel文件(xlsx)?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。