user229425
user229425

Reputation: 61

Exporting a HTML Table to Excel from ASP.NET MVC

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?

Upvotes: 5

Views: 10415

Answers (3)

Dan Atkinson
Dan Atkinson

Reputation: 11689

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.

Upvotes: 7

Naveed
Naveed

Reputation: 42093

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,[email protected],+12345,USA
Ali,[email protected],+54321,UAE
Naveed,[email protected],+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

:)

Upvotes: 1

Alexander Shvetsov
Alexander Shvetsov

Reputation: 639

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#

Upvotes: 1

Related Questions