English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation of generating Excel and download function with Asp.net MVC

This article shares the specific code for generating and downloading Excel files using Asp.net MVC, for everyone's reference, the specific content is as follows

Due to the requirements of the project, it is necessary to export Excel files with specified conditions. After some trouble, it has finally been realized.

Now, let's post the code for sharing

(Here is a sharing of some auxiliary class code from our project)

Our project uses Asp.Net MVC4.0 mode.

Every ActionResult will necessarily return a View or Json (the parameters in View or Json are all of object type)

Therefore, we need a public class to define the unified definition of the 'success or failure' status of operations or return messages, and to ensure uniformity when using jquery $.get() and $.post() to receive return parameters.

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

/// <summary>
 /// Aids in the transmission of 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>
  /// <param name="messageContent">Message content</param>/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>
  /// Prompt Information
  /// </summary>
  Hint = 0,
  /// <summary>
  /// Login Prompt
  /// </summary>
  Login = 5,
  /// <summary>
  /// Redirect Prompt
  /// </summary>
  Redirect = 6,
 };

Define ExportExcel ActionResult in the 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 = "";
   //Organize Excel table
   StringBuilder sb = new StringBuilder(400);
   sb.Append("<table cellspacing='0' rules='all' border='1'>");
   sb.Append("<thead>");
   sb.Append("<tr>");
   sb.Append("<th>Column 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>");
    //Using UTF8Format the content into a file
    byte[] contentBytes = Encoding.UTF8.GetBytes(sb.ToString());
    string rootDirServerPath = "The generated files will be saved in the specified directory name";
    //Since there is basically no concurrency in downloading Excel files in our project, we can avoid the problem of generating duplicate file names by using the year, month, day, hour, minute, and second to name the file.
    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 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 = "Downloading, please wait...";
   result.Data = fileglobal;
   return Json(result);
  }; 

After completing the generation of Excel, perform 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 operation
        };
      });
    });
  });

The above is all the operations about Excel generation and download in our project.

The considerations are relatively few, and the writing is relatively simple.

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

Thank you very much.

That's all for this article, I hope it will be helpful to everyone's study, and I also hope everyone will support the Shouting Tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, nor has it been manually edited, nor does it assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You may also like