试图通过ajax调用返回excel文件,但有些地方不对劲。jquery代码正好落在错误块中。
mvc控制器
public ActionResult GetExceptionBillingExport(BillableStopSearchFilter bFilter)
{
var results = GetDataFromDatabase();
using (var package = new ExcelPackage())
{
ExcelWorksheet sheet = package.Workbook.Worksheets.Add("Sheet1");
sheet.Cells.LoadFromCollection(results, true);
return File(package.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
}
}
jQuery方法
$.ajax({
type: 'GET',
url: 'controller-url-here',
data: filter,
beforeSend: function () {
},
complete: function () {
},
success: function (response) {
console.log(response);
var blob = new Blob([response], { type: 'application/vnd.ms-excel' });
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "Report.xlsx";
document.body.appendChild(a);
a.click();
},
error: function (err) {
alert(err);
}
});
工作正常。关键的变化是:(1(用Json封装响应,然后(2(在创建Blob 之前拆包阵列
jQuery:
$.ajax({
type: 'POST',
url: '@Url.Action("GetBillingExport", "BillingExceptions")',
data: searchFilterData,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
},
complete: function () {
},
success: function (response) {
console.log(response);
var bytes = new Uint8Array(response.FileContents);
var blob = new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "Report.xlsx";
document.body.appendChild(a);
a.click();
},
error: function (err) {
alert(err);
},
cache: false
});
控制器:
[System.Web.Http.HttpPost]
public ActionResult GetBillingExport([FromBody] BillableStopSearchFilter searchFilterData)
{
var results = GetDataFromDatabase(BillableStopSearchFilter);
ExcelPackage.LicenseContext = LicenseContext.Commercial;
using (var package = new ExcelPackage())
{
ExcelWorksheet sheet = package.Workbook.Worksheets.Add("BillingReport");
sheet.Cells.LoadFromCollection(results, true);
package.Save();
var fileObject = File(package.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
return Json(fileObject, JsonRequestBehavior.AllowGet);
}
}