5

I am currently working with ASP.NET MVC and I have an action method that displays few reports in the view in table format.

I have a requirement to export the same table to an Excel document at the click of a button in the View.

How can this be achieved? How would you create your Action method for this?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
user229425
  • 61
  • 1
  • 1
  • 4

3 Answers3

7

In your controller action you could add this:

Response.AddHeader("Content-Disposition", "filename=thefilename.xls");
Response.ContentType = "application/vnd.ms-excel";

Then just send the user to the same view. That should work.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
  • 4
    Works, thanks. Just a note, Excel complains about content being in a different format than the extension. – Brian Low Nov 05 '12 at 17:52
1

I'm using component, called Aspose.Cells (http://www.aspose.com/categories/.net-components/aspose.cells-for-.net/).

It's not free, though the most powerful solution I've tried +)

Also, for free solutions, see: Create Excel (.XLS and .XLSX) file from C#

Community
  • 1
  • 1
1

Get data from database using your data access methods in dot net.

Use a loop to get each record.

Now add each record in a variable one by one like this.

Name,Email,Phone,Country
John,john@john.com,+12345,USA
Ali,ali@ali.com,+54321,UAE
Naveed,naveed@naveed.com,+09876,Pakistan

use 'new line' code at the end of each row (For example '\n')

Now write above data into a file with extension .csv (example data.csv)

Now open that file in EXCEL

:)

Naveed
  • 41,517
  • 32
  • 98
  • 131