Asp. net MVC Implementation Generate Excel and Download Function

  • 2021-10-15 10:23:24
  • OfStack

This article example for everyone to share Asp. net MVC implementation to generate Excel and download the specific code, for your reference, the specific content is as follows

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

Now post the code and share it

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

Our project uses the Asp. Net MVC 4.0 schema.

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

Therefore, we need a common class to define the "success or failure" status of an operation or the message that returns the operation, as well as the uniformity when receiving return parameters that are beneficial to using 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>
  ///  Errors 
  /// </summary>
  Error = -1,

  /// <summary>
  ///  Prompt information 
  /// </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 Forms 
   StringBuilder sb = new StringBuilder(400);
   sb.Append("<table cellspacing='0' rules='all' border='1'>");
   sb.Append("<thead>");
   sb.Append("<tr>");
   sb.Append("<th> Column 1</th>");
   sb.Append("<th> Column 2</th>");
   sb.Append("<th> Column 3</th>");
   sb.Append("<th> Column 4</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 = " Saves the generated file in the specified directory name ";
    // Due to the download on our project Excel There is basically no concurrency in files, so only naming files by year, month, day, hour and second can avoid the problem of generating files with the same file name. 
    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);
     }
    }
    // Here is how to save a 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 be downloaded. 
    fileglobal = rootDirServerPath + "/" + fileSaveName;
   }
   catch (Exception ex)
   {
    result.MessageType = StatusMessageType.Error;
    result.MessageContent = ex.Message.ToString();
    return Json(result);
   }
   result.MessageType = StatusMessageType.Success;
   result.MessageContent = " Please wait while you download ...";
   result.Data = fileglobal;
   return Json(result);
  } 

After the operation of generating Excel is completed, asynchronous call is made 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 operation 
        }
      });
    });
  });

These are all the operations from Excel generation to download in our project.

Consider the situation is less, write relatively simple.

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

Thank you very much.


Related articles: