Nei*_*eil 18 c# asp.net excel xls asp.net-web-api
我正在尝试发送一个9MB的.xls
文件作为web api控制器方法的响应.用户将单击页面上的按钮,这将通过浏览器触发下载.
这是我到目前为止所得到的,但它不起作用,但它也没有抛出任何例外.
[AcceptVerbs("GET")]
public HttpResponseMessage ExportXls()
{
try
{
byte[] excelData = m_toolsService.ExportToExcelFile();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(excelData);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Data.xls"
};
return result;
}
catch (Exception ex)
{
m_logger.ErrorException("Exception exporting as excel file: ", ex);
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
Run Code Online (Sandbox Code Playgroud)
这是通过界面中的按钮单击调用coffeescript/javascript jquery ajax.
$.ajax(
url: route
dataType: 'json'
type: 'GET'
success: successCallback
error: errorCallback
)
Run Code Online (Sandbox Code Playgroud)
现在我想到它也许dataType是错误的,不应该是json ...
Nei*_*eil 12
我不得不进行一些小改动才能让它发挥作用
第一:将方法更改为帖子
[AcceptVerbs("POST")]
Run Code Online (Sandbox Code Playgroud)
第二:从使用jQuery ajax lib改为使用隐藏表单,这是我的服务函数,用于执行隐藏表单并提交它.
exportExcel: (successCallback) =>
if $('#hidden-excel-form').length < 1
$('<form>').attr(
method: 'POST',
id: 'hidden-excel-form',
action: 'api/tools/exportXls'
).appendTo('body');
$('#hidden-excel-form').bind("submit", successCallback)
$('#hidden-excel-form').submit()
Run Code Online (Sandbox Code Playgroud)
希望有更好的方法来做到这一点,但暂时它正在工作并很好地下载excel文件.
Leo*_*Leo 12
也可以作为HTTP GET方法,但不要使用$ ajax,而是使用window.open(url);
C#代码:
[HttpGet]
[Route("report/{scheduleId:int}")]
public HttpResponseMessage DownloadReport(int scheduleId)
{
var reportStream = GenerateExcelReport(scheduleId);
var result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(reportStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Schedule Report.xlsx"
};
return result;
}
Run Code Online (Sandbox Code Playgroud)
JS代码:
downloadScheduleReport: function (scheduleId) {
var url = baseUrl + 'api/Tracker/report/' + scheduleId;
window.open(url);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43726 次 |
最近记录: |