how to export asp.net MVC detail view data to an excel file?
How to export ASP.NET MVC view data to an excel file ? Actually my view page contain many viewdata types. I am using for each loop with these datatype to displaying data on the view page. My r开发者_如何学Cequirement is that I want to export this displayed data into Excel file. How do I achieve this?
Thanks
Look at http://blogs.msdn.com/erikaehrli/archive/2009/01/30/how-to-export-data-to-excel-from-an-asp-net-application-avoid-the-file-format-differ-prompt.aspx.
After some experiments I use Open XML SDK 2.0. You can find currently a lot of information how to do this on http://msdn.microsoft.com/en-us/office/aa905545.aspx and http://openxmldeveloper.org/. One more link http://extrememl.codeplex.com/ can be also useful.
Usage of Open XML SDK 2.0 at the first time take a little more time as other ways, but exported files are real Excel files and should not be converted by users. And if you will be have more requirements for the format of produced excel files, you will be able to implement there.
You could loop through the Keys/Values of your ViewData and generate the excel file (various options mentioned Here) or simply to CSV
But I would recommend rather doing this in the controller and returning a FileResult and not from the ViewData (which I presume you using in your View).
Depending on the complexity of the page's HTML you might be able to get away with just changing the header type to application/excel
. Excel has built in html parsing functionality. I've successfully done this many times a few years back with a DataGrid on a page.
Response.ContentType = "application/excel"
Response.AppendHeader "content-disposition", "attachment: filename=TestExcelFile.xls"
Some details on HTML in excel
精彩评论