Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 276
user229425 Avatar asked Dec 19 '09 10:12

user229425


People also ask

How do I export data from HTML table to Excel?

To convert HTML table data into excel, we need to use the SheetJS library. Using SheetJs we can easily convert our table data into an Xls file. We can download the js file from Github or directly use the CDN hosted file. We are done with HTML markup and import Sheetjs library.


3 Answers

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.

like image 165
Dan Atkinson Avatar answered Sep 29 '22 11:09

Dan Atkinson


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#

like image 36
Alexander Shvetsov Avatar answered Sep 29 '22 12:09

Alexander Shvetsov


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

:)

like image 21
Naveed Avatar answered Sep 29 '22 11:09

Naveed