1

I'm trying to download a closedXml excel file in a webapi/angularjs application.

I'm returning the data from the webapi controller on the server using:

 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;

and then saving it on the client using:

$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 says the file is in a different format than specified by the extension and then doesn't open properly.

1 Answer 1

0

On projects I work on, I make a Controller for files(not an 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");
    }
}

and then from angular, I open the file like this

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.