[英].NET C# exporting to excel via JS post using ExcelPackage
I'm not sure what I'm missing here. 我不确定我在这里缺少什么。 I've got a button that when clicked, I'm using javascript to call a controller. 我有一个按钮,当单击该按钮时,我正在使用javascript调用控制器。 This controller should create an excel file and return it to the user giving them the ability to download/save the file. 该控制器应创建一个excel文件,并将其返回给用户,使他们能够下载/保存文件。 I've tried a few different methods, but can't manage to get it to work. 我尝试了几种不同的方法,但无法使其正常工作。 Here's my javascript side: 这是我的JavaScript面:
function exportList() {
var val = $("#team-dropdown").val();
const date = new Date().toISOString();
const param = {
"Date": date,
"GroupID": 1
}
$.ajax({
url: "@Url.Action("ExportToExcel", "Home")",
type: "POST",
data: param
});
}
Here's my server side: 这是我的服务器端:
public FileResult ExportToExcel(DateTime date, int groupID)
{
Load l = new Load();
List<Load> loadList = l.GetLoadsForGroup(date, groupID);
var fileDownloadName = "fileName.xlsx";
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("New workbook");
ws.View.ShowGridLines = true;
ws.DefaultColWidth = 25;
ws.Cells[1, 1].Value = "Order #";
var currRow = 2;
foreach (var load in loadList)
{
ws.Cells[2, 2].Value = load.LoadNumber;
}
var fs = new MemoryStream();
pck.SaveAs(fs);
fs.Position = 0;
var fsr = new FileStreamResult(fs, contentType);
fsr.FileDownloadName = fileDownloadName;
return (fsr);
}
Not sure what the best way to do this is. 不确定执行此操作的最佳方法是什么。 If there's a better way, please feel free to elaborate. 如果有更好的方法,请随时详细说明。
Your method looks fine. 您的方法看起来不错。 In that case you just need to use a html form
to post instead of using the js function. 在这种情况下,您只需要使用html form
发布即可,而不是使用js函数。 Alternatively, if you would like to use a ActionResult
you can write: 另外,如果您想使用ActionResult
,可以编写:
public ActionResult ExportToExcel()
{
Load l = new Load();
List<Load> loadList = l.GetLoadsForGroup(date, groupID);
var fileDownloadName = "fileName.xlsx";
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("New workbook");
ws.View.ShowGridLines = true;
ws.DefaultColWidth = 25;
ws.Cells[1, 1].Value = "Order #";
var currRow = 2;
foreach (var load in loadList)
{
ws.Cells[2, 2].Value = load.LoadNumber;
}
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileDownloadName + "\"");
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush();
Response.End();
return View();
}
And you get the same result as your method. 您将获得与您的方法相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.