使用 webapi 和 angularjs 下载 excel 文件

Download excel file using webapi and angularjs

我正在尝试在 webapi/angularjs 应用程序中下载一个 closedXml excel 文件。

我使用以下方法从服务器上的 webapi 控制器返回数据:

 HttpResponseMessage result = new HttpResponseMessage();
 result = Request.CreateResponse(HttpStatusCode.OK);
 MemoryStream stream = GetStream(workbook);
 result.Content = new StreamContent(stream);
 result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
 result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
 {
     FileName = "Download.xlsx"
 };
 return result;

然后使用以下方法将其保存在客户端上:

$scope.openExcel =  function (data, status, headers, deferred) {
        var type = headers('Content-Type');
        var disposition = headers('Content-Disposition');
        if (disposition) {
            var match = disposition.match(/.*filename=\"?([^;\"]+)\"?.*/);
            if (match[1])
                defaultFileName = match[1];
        }
        defaultFileName = defaultFileName.replace(/[<>:"\/\|?*]+/g, '_');
        var blob = new Blob([data], { type: type });

        saveAs(blob, defaultFileName);

Excel 表示该文件的格式与扩展名指定的格式不同,因此无法正常打开。

在我从事的项目中,我为文件制作了一个控制器(不是 ApiController)

public class FilesController : Controller
{
    public FileResult GetFile(/*params*/)
    {
        // get fileBytes
        var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        return base.File(fileBytes, contentType, "Download.xlsx");
    }
}

然后从angular开始,我这样打开文件

$window.open("/Files/GetFile/" /*+ params*/);