Thursday, September 3, 2015

.NET Excel File Download

This was a cool trick I learned from a co-worker, which he in turn found from StackOverflow. I'm putting it here as a reference, because it's so simple and useful. So, let's say you want to have the browser download an Excel file instantly without using plugins or Interop. You put the following lines in your controller method:
Response.AddHeader("content-disposition", "attachment; filename=" + [filename]);
Response.ContentType = "application/ms-excel";
Then you have the method return a PartialView. The PartialView will have an IEnumerable of your view model:
@model IEnumerable<[view_model_here]>
Then you can just add the markup and styling for the data. When you run the application and use the controller method, it will cause a download attachment to occur.

Like I said, cool.

No comments:

Post a Comment