ASP. NET MVC simple implementation generates Excel and downloads

Source: Internet
Author: User

Because of the requirements on the project, you need to export the Excel file for the specified criteria. After a turn toss finally realized.

Now put the code out to share

(Share the code of the auxiliary class directly in our project)

Our project is using the ASP. NET MVC4.0 mode.

Each actionresult is bound to return a view or JSON, etc. (parameters in view or JSON are of type object)

So we need a common class to uniformly define the "success or failure" state of the operation or the message that returns the operation, and the unity that facilitates the use of jquery $.get (), $.post () to receive return parameters.

The following is the Statusmessagedata class. (Of course, if you only want to export Excel, this class doesn't need to be defined.) )

/// <summary>   ///Secondary transfer of StatusMessage data/// </summary>[Serializable] Public Sealed classStatusmessagedata {PrivateStatusmessagetype MessageType; /// <summary>      ///Prompt Message category/// </summary>       Publicstatusmessagetype MessageType {Get{returnMessageType;} Set{MessageType =value;} }      Private stringMessagecontent =string.      Empty; /// <summary>      ///Information Content/// </summary>       Public stringmessagecontent {Get{returnmessagecontent;} Set{messagecontent =value;} }      Private Objectdata; /// <summary>      ///Data/// </summary>       Public ObjectData {Get{returndata;} Set{data =value;} }      /// <summary>      ///Constructors/// </summary>      /// <param name= "MessageType" >Message Type</param>      /// <param name= "Messagecontent" >Message Content</param>       PublicStatusmessagedata (Statusmessagetype MessageType,stringMessagecontent,Objectdata) {          This. MessageType =MessageType;  This. messagecontent =messagecontent;  This. data =data; }       PublicStatusmessagedata (Statusmessagetype MessageType,stringmessagecontent) {          This. MessageType =MessageType;  This. messagecontent =messagecontent; }       PublicStatusmessagedata () {}}/// <summary>   ///Prompt Message category/// </summary>    Public enumStatusmessagetype {/// <summary>      ///Success/// </summary>Success =1,      /// <summary>      ///Error/// </summary>Error =-1,      /// <summary>      ///Prompt Information/// </summary>Hint =0,      /// <summary>      ///Reminder Login/// </summary>Login =5,      /// <summary>      ///Prompt Redirection/// </summary>Redirect =6,   }
View Code

Define the Exportexcel ActionResult in the controller

[HttpPost] PublicActionResult Exportexcel (Searchmodel model) {statusmessagedata result=NewStatusmessagedata (); if(model. Data = =NULL|| Model. Data.count <=0) {result. MessageType=Statusmessagetype.error; Result. Messagecontent="no data to download"; returnJson (Result); }            stringFileglobal =""; //Organize Excel tablesStringBuilder SB =NewStringBuilder ( -); Sb. Append ("<table cellspacing= ' 0 ' rules= ' all ' border= ' 1 ' >"); Sb. Append ("<thead>"); Sb. Append ("<tr>"); Sb. Append ("<th> List One </th>"); Sb. Append ("<th> column two </th>"); Sb. Append ("<th> column three </th>"); Sb. Append ("<th> Column IV </th>"); Sb. Append ("</tr>"); Sb. Append ("</thead>"); Sb. Append ("<tbody>"); Try            {                        foreach(varIteminchmodel. Data) {sb. Append ("<tr>"); Sb. Append ("<td>"); Sb.                            Append (ITEM.COLUMN1); Sb. Append ("</td>"); Sb. Append ("<td>"); Sb.                            Append (ITEM.COLUMN2); Sb. Append ("</td>"); Sb. Append ("<td>"); Sb.                            Append (ITEM.COLUMN3); Sb. Append ("</td>"); Sb. Append ("<td>"); Sb.                            Append (ITEM.COLUMN4); Sb. Append ("</td>"); Sb. Append ("</tr>"); }} sb. Append ("</tbody>"); Sb. Append ("</table>"); //writing files in UTF8 format                byte[] Contentbytes =Encoding.UTF8.GetBytes (sb.)                ToString ()); stringRootdirserverpath ="saves the generated file in the specified directory name"; //since there is basically no concurrency in downloading Excel files on our project, it is only possible to name the files by the day of the month and days to avoid the problem of generating the same file name files.                 stringFilesavename ="Download the file name _"+ DateTime.Now.ToString ("YYYYMMDDHHMMSS") +". xls"; stringRootdirserverphysicpath = Server.MapPath ("~"+Rootdirserverpath); if(!directory.exists (Rootdirserverphysicpath))                {directory.createdirectory (Rootdirserverphysicpath); }                string[] Strfiles =Directory.GetFiles (Rootdirserverphysicpath); if(Strfiles.length >0)                {                    foreach(stringStrfileinchstrfiles)                    {System.IO.File.Delete (strfile); }                }                //here's how to save the file to the specified directory                stringUserfailedsummaryfilesavepath = Rootdirserverphysicpath +"/"+Filesavename; if(System.IO.File.Exists (Userfailedsummaryfilesavepath)) {System.IO.File.Delete (user                Failedsummaryfilesavepath);                } System.IO.File.WriteAllBytes (Userfailedsummaryfilesavepath, contentbytes); //assemble the full path to the file you want to download. Fileglobal = Rootdirserverpath +"/"+Filesavename; }            Catch(Exception ex) {result. MessageType=Statusmessagetype.error; Result. Messagecontent=Ex.                Message.tostring (); returnJson (Result); } result. MessageType=statusmessagetype.success; Result. Messagecontent="downloading, please wait ..."; Result. Data=Fileglobal; returnJson (Result); } 
View Code

After you have finished generating Excel, make an asynchronous call on the page.

$ ("#export-excel"). Click (function (e) {        e.preventdefault ();        $.post ("Controller/exportexcel.aspx", $ ("#Form1"). Serialize (), function (data) {            art.dialog.tips (data). Messagecontent, 1.5, data. MessageType, function () {                if (data). MessageType = = 1) {                    window.open (data. Data);                } else {                    //Error action                }            }        )    ;});
View Code

These are all the actions we have in our project about Excel generation to download.

The situation is relatively small, the writing is relatively simple.

If you have any good ideas, you can leave a message, I will certainly learn and practice good again to share.

Thank you so much.

If you have help, please praise!

ASP. NET MVC simple implementation generates Excel and downloads

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.