MVC exports data to Excel new method: Convert view or partial view to HTML before returning directly to Fileresult

Source: Internet
Author: User

New ways to export data to Excel: Convert a View or partial view to HTML and return directly to the Fileresult export Excel method Summary:
There are many ways in which MVC exports data to Excel, which is common:


1. Use the Excel COM component to dynamically generate the XLS file and save it to the server, then go to the file storage path;
Advantages: You can set rich Excel format, disadvantage: Need to rely on Excel components, and Excel process in the server can not close in time, and the server will persist a large number of unnecessary XLS files;


2. Set the output header to: Application/ms-excel, and then output the stitching HTML table data;
Advantages: No components, can set some simple format, disadvantage: Splicing HTML table process is more complex, not intuitive;


3. With third-party components (e.g., npoi)
The pros and cons are dependent on the ease of use of third-party components and are not described here;

Implementing a new Export Excel method under MVC
Here is a new way to share in MVC: Convert a View or partial view to HTML and return directly to Fileresult to easily export Excel functionality;

First look at the contents of the partial view (indexdatalist):

@model Ienumerable<ccps. Models.data.customercommentinfo>@using Pagedlist.mvc;<table> <thead> <tr> <th> opinions id</th> <th> Organization </th> <th> license plate </th> <th> models </th> <th> Royal version </th> <t H> Customer </th> <th> Customer Phone </th> <th> Responsible Department </th> <th> responsible Team <            /th> <th> Business Advisors </th> <th> opinion types </th> <th> status </th> <th> Entry Clerk </th> <th> entry Time </th> </tr> </thead> <tbody id="List-table-body">@foreach (varIteminchModel) {            stringClassName =""; if(item. Status = ="Audit not processed") {ClassName="Uncl_yellow"; if(item. Auditdatetime! =NULL&& datetime.now > (DateTime) item. Auditdatetime). AddHours ( -) ) {ClassName="uncl_red"; }            }            <trclass="@className"data-adt="@item. Auditdatetime"> <td><a href="Http://oa.pfcn.com/flow/[email protected]&flow_id=147"target="_blank"> @item. id</a></td> <td> @item .orgname</td> <td> @item. Plateno</td> <td> @item. Model</td> <td> @item. Isroyalver</td> <td> @item. Customername</td> <td> @item. Customerphoneno</td> <td> @item. Relevantdept</td> <td> @item. Relevantgroup</td> <td> @item. Consultant</td> <td> @item. Type</td> <td> @item. Status</td> <td> @item. Createby</td> <td> @string. Format ("{0:g}", item. Createdatetime) </td> </tr>        }    </tbody></table>@if (true!=viewbag.nopaging) { <divclass="Pager">@Html. Pagedlistpager (Model asPagedlist.ipagedlist<ccps. models.data.customercommentinfo>, page =string. Format ("javascript:turnpage ({0});", page), Pagedlistrenderoptions.classicplusfirstandlast)</div>}

My partial view here is not just for exporting Excel, so I can use it when I display the data with the main views, so I have a page to judge if I export Excel, that certainly does not need paging.
Here's how to implement generating HTML for a view, a partial view, with the following code:

[Nonaction]protected stringRenderviewtostring (Controller controller,stringViewName,stringmastername) {IView View=ViewEngines.Engines.FindView (Controller. ControllerContext, ViewName, Mastername).            View; using(StringWriter writer =NewStringWriter ()) {ViewContext ViewContext=NewViewContext (Controller. ControllerContext, view, controller. ViewData, Controller.                TempData, writer);                ViewContext.View.Render (ViewContext, writer); returnwriter.            ToString (); }} [Nonaction]protected stringRenderpartialviewtostring (Controller controller,stringpartialviewname) {IView View=ViewEngines.Engines.FindPartialView (Controller. ControllerContext, Partialviewname).            View; using(StringWriter writer =NewStringWriter ()) {ViewContext ViewContext=NewViewContext (Controller. ControllerContext, view, controller. ViewData, Controller.                TempData, writer);                ViewContext.View.Render (ViewContext, writer); returnwriter.            ToString (); }        }

These two methods are implemented according to the steps and principles of their view rendering, the general step is: Find View--materialized view context--render view to output container
Finally, you define an action method that exports Excel and return Fileresult, which completes the export of Excel functionality, with the following code:

         PublicActionResult Export (datafilter<customercommentinfo>[] filters) {            varResultlist = Dataprovider.getcustomercommentinfos (filters). (t =t.createdatetime); Viewbag.nopaging=true; Viewdata.model=resultlist; stringviewhtml = renderpartialviewtostring ( This,"indexdatalist"); returnFile (System.Text.Encoding.UTF8.GetBytes (viewhtml),"Application/ms-excel",string. Format ("Ccpi_{0}.xls", Guid.NewGuid ())); }

Isn't it simple? To export what kind of Excel format content, directly can be in the view of the design is OK.

MVC exports data to Excel new method: Convert a view or partial view to HTML and then return directly to Fileresult

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.