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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works, thanks. Just a note, Excel complains about content being in a different format than the extension.
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#

Comments

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,[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

:)

2 Comments

What if the values contain comma?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.