下载Excel文件与WebAPI/MVC

本文关键字:MVC WebAPI Excel 文件 下载 | 更新日期: 2023-09-27 18:05:28

我试图通过WebAPI下载Excel文件。基本上Excel文件是通过内存流创建的,在这篇文章的帮助下

Excel内容生成良好,但我无法下载Excel作为响应本身是纯XML,当我看到它在Chrome网络工具的响应选项卡。下面是我的c#代码

var sheet = linq.ExportToExcel(userAddedList);

            var stream = new MemoryStream();
            var sw = new StreamWriter(stream);
            sw.Write(sheet);
            sw.Flush();
            var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.GetBuffer()) };
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Report.xml" };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
            var response = ResponseMessage(result);
            return response;

这就是我在Angular中调用它的方式。

var httpRequest = commonFunctions。gettrequestobject ("GET", requestURL, {}, null);

        $http(httpRequest).then(function (response) {
            vm.isProcessing = false;
        }, function (error) { displayError(error); });

下载Excel文件与WebAPI/MVC

如果目标浏览器支持File API,则可以使用Blob对象。这里,它被封装在一个函数中,取自这个小提琴:

var setFile = function( data, fileName, fileType ) {
    // Set objects for file generation.
    var blob, url, a, extension;
    // Get time stamp for fileName.
    var stamp = new Date().getTime();
    // Set MIME type and encoding.
    fileType = ( fileType || "text/csv;charset=UTF-8" );
    extension = fileType.split( "/" )[1].split( ";" )[0];
    // Set file name.
    fileName = ( fileName || "ActiveVoice_" + stamp + "." + extension );
    // Set data on blob.
    blob = new Blob( [ data ], { type: fileType } );
    // Set view.
    if ( blob ) {
        // Read blob.
        url = window.URL.createObjectURL( blob );
        // Create link.
        a = document.createElement( "a" );
        // Set link on DOM.
        document.body.appendChild( a );
        // Set link's visibility.
        a.style = "display: none";
        // Set href on link.
        a.href = url;
        // Set file name on link.
        a.download = fileName;
        // Trigger click of link.
        a.click();
        // Clear.
        window.URL.revokeObjectURL( url );
    } else {
        // Handle error.
    }
};

你可以像这样使用它作为你代码的一部分:

$http(httpRequest).then(function (response) {
    vm.isProcessing = false;
    setFile(response.data, "Report.xls", "application/ms-excel");
}, function (error) { displayError(error); });