Jquery 使用对web API的AJAX调用导出到Excel
我有以下AJAX调用:Jquery 使用对web API的AJAX调用导出到Excel,jquery,ajax,asp.net-web-api,Jquery,Ajax,Asp.net Web Api,我有以下AJAX调用: function exportToExcel() { $.ajax({ type: "GET", dataType: "json", url: "../api/Unit/Export/", success: function () { downloadExcel(); }, error: function () { console.e
function exportToExcel() {
$.ajax({
type: "GET",
dataType: "json",
url: "../api/Unit/Export/",
success: function () {
downloadExcel();
},
error: function () {
console.error("Error exporting");
}
});
}
这将转到控制器类中的以下C#代码:
[Route("api/Unit/Export/")]
[HttpGet]
public HttpResponseMessage Export() {
try {
WorkbookFormats formats = new WorkbookFormats();
List<ExcelWorksheetData> wbData = new List<ExcelWorksheetData>();
MemoryStream ms = ExcelExportService.CreateSpreadsheetWorkbook(wbData, formats);
string fileName = "DemoExcel.xlsx";
byte[] dt = ms.ToArray();
HttpResponseMessage response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
response.Content = new ByteArrayContent(dt);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;//your file Name- text.xls
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
response.Content.Headers.ContentLength = dt.Length;
return response;
} catch (Exception ex) {
return null;
}
}
[路径(“api/单元/导出/”)
[HttpGet]
公共HttpResponseMessage导出(){
试一试{
WorkbookFormats=新的WorkbookFormats();
List wbData=新列表();
MemoryStream ms=ExcelExportService.CreateSpreadsheetWorkbook(wbData,格式);
字符串fileName=“DemoExcel.xlsx”;
字节[]dt=ms.ToArray();
HttpResponseMessage response=Request.CreateResponse(System.Net.HttpStatusCode.OK);
response.Content=newbytearraycontent(dt);
response.Content.Headers.ContentDisposition=新的ContentDispositionHeaderValue(“附件”);
response.Content.Headers.ContentDisposition.FileName=FileName;//您的文件名-text.xls
response.Content.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/ms excel”);
response.Content.Headers.ContentLength=dt.Length;
返回响应;
}捕获(例外情况除外){
返回null;
}
}
我注意到,响应是由C#代码返回的,但在Ajax调用中,它似乎从未达到成功的条件
任何指针都将不胜感激。您是否可以尝试使用POST而不是GET,并返回json字符串。