c# - 通过 WebApi 调用从页面下载 excel 文件

标签 c# asp.net excel asp.net-web-api xls

我正在尝试发送一个 9MB 的 .xls 文件作为来自 web api Controller 方法的响应。用户将单击页面上的按钮,这将通过浏览器触发下载。

这是我到目前为止所得到的,但它不起作用,但它也不会抛出任何异常。

[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);
    }
}

这是从界面中的按钮点击调用的 coffeescript/javascript jquery ajax。

$.ajax(
    url: route
    dataType: 'json'
    type: 'GET'
    success: successCallback
    error: errorCallback 
    )

现在想想可能是dataType不对,不应该是json...

最佳答案

也可以用作 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;
    }

JS代码:

downloadScheduleReport: function (scheduleId) {
    var url = baseUrl + 'api/Tracker/report/' + scheduleId;
    window.open(url);
}

关于c# - 通过 WebApi 调用从页面下载 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14831860/

相关文章:

c# - 我应该如何在 Controller 中模拟 SignalR HubContext 以进行单元测试?

asp.net - 如何在 ASP.NET 的服务器端获取输入值(输入文本)?

javascript - 为什么取消输入提交而不是使用输入类型 ='button'

excel - 锁定 Access 表以防止在特定时间进行写入

c# - 在 sqlConnections 上使用 'Using' 对性能有何影响

c# - MVC - 表单例份验证、IFrame cookie、动态 Cookieless 模式

c# - 我可以在 .Net/C# 中为 R 编写库/包吗?

c# - 如何在托管 Windows 服务中托管 WCF 服务?

c# - 在c#中从excel中获取jpeg格式的图像

c# - 如何读取一系列单元格(例如 A1 :G30) from Excel file to GridView