使用WebAPI / MVC下载Excel文件

时间:2016-09-02 16:11:51

标签: c# angularjs excel linq asp.net-web-api

我正在尝试通过WebAPI下载Excel文件。基本上Excel文件是借助于此Post

通过Memory Stream创建的

Excel内容正在生成正常但我无法下载Excel,因为当我在Chrome网络工具的“响应”选项卡中看到它时,响应本身就是纯XML。以下是我的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.getRequestObject(“GET”,requestURL,{},null);

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

1 个答案:

答案 0 :(得分:1)

如果您定位的浏览器支持File API,则可以使用Blob object。它包含在一个函数中,取自this fiddle

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