Asp.net MVC simple implementation generate Excel and download

Due to the requirements on the project, you need to export the Excel file with the specified conditions. After a rummage, it finally came true.

Now post the code and share it

(directly share the code of some auxiliary classes in our project)

 

Our project uses Asp.Net MVC4.0 mode.

Each ActionResult must return a View or Json, etc. (the parameters in View or Json are of object type)

Therefore, we need a common class to uniformly define the "success or failure" status of the operation or the message of the return operation, as well as the uniformity when receiving the return parameters in favor of jquery $.get(), $. post().

The following is the StatusMessageData class. (of course, if you only want to export Excel, this class does not need to be defined. )

/// <summary>
   /// Auxiliary transmission StatusMessage data
   /// </summary>
   [Serializable]
   public sealed class StatusMessageData
   {
      private StatusMessageType messageType;
      /// <summary>
      /// Prompt message category
      /// </summary>
      public StatusMessageType MessageType
      {
         get { return messageType; }
         set { messageType = value; }
      }

      private string messageContent = string.Empty;
      /// <summary>
      /// information content
      /// </summary>
      public string MessageContent
      {
         get { return messageContent; }
         set { messageContent = value; }
      }

      private object data;

      /// <summary>
      /// data 
      /// </summary>
      public object Data
      {
         get { return data; }
         set { data = value; }
      }
      /// <summary>
      /// constructor 
      /// </summary>
      /// <param name="messageType">Message type</param>
      /// <param name="messageContent">Message content</param>
      public StatusMessageData(StatusMessageType messageType, string messageContent, object data)
      {
         this.messageType = messageType;
         this.messageContent = messageContent;
         this.data = data;
      }
      public StatusMessageData(StatusMessageType messageType, string messageContent)
      {
         this.messageType = messageType;
         this.messageContent = messageContent;
      }
      public StatusMessageData()
      {
      }
   }

   /// <summary>
   /// Prompt message category
   /// </summary>
   public enum StatusMessageType
   {
      /// <summary>
      /// Success
      /// </summary>
      Success = 1,

      /// <summary>
      /// error
      /// </summary>
      Error = -1,

      /// <summary>
      /// Tips
      /// </summary>
      Hint = 0,
      /// <summary>
      /// Remind login
      /// </summary>
      Login = 5,
      /// <summary>
      /// Prompt redirection
      /// </summary>
      Redirect = 6,
   }

 

Define ExportExcel ActionResult in Controller

[HttpPost]
        public ActionResult ExportExcel(SearchModel model)
        {
            
           
            StatusMessageData result = new StatusMessageData();
            if (model.Data == null || model.Data.Count <= 0)
            {
                result.MessageType = StatusMessageType.Error;
                result.MessageContent = "No data to download";
                return Json(result);
            }
            string fileglobal = "";
            //organization Excel form
            StringBuilder sb = new StringBuilder(400);
            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 four</th>");
            sb.Append("</tr>");
            sb.Append("</thead>");
            sb.Append("<tbody>");
            try
            {
                        foreach (var item in model.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>");
                //with UTF8 Format write file
                byte[] contentBytes = Encoding.UTF8.GetBytes(sb.ToString());

                string rootDirServerPath = "Save the generated file in the specified directory name";
                //Due to our project Download Excel There is no concurrency in files, so the problem of generating files with the same file name can be avoided only by naming files with month, day, hour, minute and second.
                string fileSaveName = "Downloaded file name_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

                string rootDirServerPhysicPath = Server.MapPath("~" + rootDirServerPath);
                if (!Directory.Exists(rootDirServerPhysicPath))
                {
                    Directory.CreateDirectory(rootDirServerPhysicPath);
                }
                string[] strFiles = Directory.GetFiles(rootDirServerPhysicPath);
                if (strFiles.Length > 0)
                {
                    foreach (string strFile in strFiles)
                    {
                        System.IO.File.Delete(strFile);
                    }
                }
                //The following is to save the file to the specified directory
                string userFailedSummaryFileSavePath = rootDirServerPhysicPath + "/" + fileSaveName;
                if (System.IO.File.Exists(userFailedSummaryFileSavePath))
                {
                    System.IO.File.Delete(userFailedSummaryFileSavePath);
                }
                System.IO.File.WriteAllBytes(userFailedSummaryFileSavePath, contentBytes);
                //Assemble the full path of the file to download.
                fileglobal = rootDirServerPath + "/" + fileSaveName;
            }
            catch (Exception ex)
            {
                result.MessageType = StatusMessageType.Error;
                result.MessageContent = ex.Message.ToString();
                return Json(result);
            }
            result.MessageType = StatusMessageType.Success;
            result.MessageContent = "Downloading, please wait...";
            result.Data = fileglobal;
            return Json(result);
        } 

 

After the operation of generating Excel is completed, it is called asynchronously 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 {
                    //Wrong operation
                }
            });
        });
    });

 

The above is all the operations from Excel generation to download in our project.

The consideration is less and the writing is simpler.

If you have any good ideas, you can leave a message, I will definitely learn and practice before sharing.

Thank you very much.

If it helps you, please like it!

Keywords: ASP.NET Excel JSON JQuery encoding

Added by busterbry on Sun, 03 May 2020 03:07:20 +0300