Export CSV ActionResult for ASP.NET MVC

13 Jan

I needed to export some data as CSV file. And I decided to create an action result to return correct format. In my scenario DataTable was the best option to use as a data source.

This code snippet shows how to export a DataTable as CSV file. As you know this file format can be opened with Excel like an Excel document.

Here is the code snippet that I used.

Here how you use at your controller action…

return new CsvActionResult(dataTableObject) { FileDownloadName = "ExportedFileName.csv" };

5 Responses to Export CSV ActionResult for ASP.NET MVC


Matt Penner

February 19th, 2011 at 2:35 am

This is great, thanks! I saw many other samples of a CVS File Result but yours definitely is one of the most concise and clear. I just dropped it in my project and it worked like a charm.



March 6th, 2011 at 1:40 pm

Thanks for the great post, it worked like magic. I have been trying this for so long, nothing seemed to work.

I do have a question, though.
If I want to add another two headers above the table header
for example:
Report Title
Report Subject
Then table headers and data
and I need to have this title and subject in one merged cell, above the whole table. (I’m using csv on excel as well as other programs)
How can this be done?
Thanks a lot and keep up the good work


Cengiz Han

March 6th, 2011 at 9:15 pm

Hi Ala,
CSV is not designed to change or design Excel sheets. Excel can open CSV as an Excel sheet, if you are looking for formatting and designing Excel sheets this is not the way to do.
Except that if you want to add some other values to your CSV output, only thing you need to do is adding that cells to your datatable.


Mukesh Kumar

May 11th, 2011 at 5:09 pm

Thanks for the great post,Thank you very much.Good Job.



November 1st, 2011 at 2:57 pm

Fine example of the way it should be done. Excellent work, thanks.

Comment Form