This article has shared with you the specific code for MVC to generate Excel and download it for your reference. The specific content is as follows
Due to the requirements on the project, it is necessary to export the Excel file with the specified conditions. After a lot of trouble, it finally came true.
Now post the code and share it
(Share part of the auxiliary class code in our project directly)
Our project uses MVC4.0 mode.
Each ActionResult will inevitably return a View or Json, etc. (The parameters in View or Json are of type object)
Therefore, we need a public class to uniformly define the "success or failure" state of the operation or return the operation message, as well as the unity when receiving return parameters using jquery $.get() and $.post().
The following is the StatusMessageData class. (Of course, if you just want to export Excel, this class does not need to be defined.)
/// <summary> /// Auxiliary 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 = ; /// <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) { = messageType; = messageContent; = data; } public StatusMessageData(StatusMessageType messageType, string messageContent) { = messageType; = messageContent; } public StatusMessageData() { } } /// <summary> /// Prompt message category /// </summary> public enum StatusMessageType { /// <summary> /// success /// </summary> Success = 1, /// <summary> /// mistake /// </summary> Error = -1, /// <summary> /// Prompt message /// </summary> Hint = 0, /// <summary> /// Remind to log in /// </summary> Login = 5, /// <summary> /// Prompt redirection /// </summary> Redirect = 6, }
Defining ExportExcel ActionResult in Controller
[HttpPost] public ActionResult ExportExcel(SearchModel model) { StatusMessageData result = new StatusMessageData(); if ( == null || <= 0) { = ; = "No data to be downloaded"; return Json(result); } string fileglobal = ""; //Organize Excel tables StringBuilder sb = new StringBuilder(400); ("<table cellspacing='0' rules='all' border='1'>"); ("<thead>"); ("<tr>"); ("<th>Column One</th>"); ("<th>Column 2</th>"); ("<th>Column Three</th>"); ("<th>Column IV</th>"); ("</tr>"); ("</thead>"); ("<tbody>"); try { foreach (var item in ) { ("<tr>"); ("<td>"); (item.column1); ("</td>"); ("<td>"); (item.column2); ("</td>"); ("<td>"); (item.column3); ("</td>"); ("<td>"); (item.column4); ("</td>"); ("</tr>"); } } ("</tbody>"); ("</table>"); //Write to file in UTF8 format byte[] contentBytes = Encoding.(()); string rootDirServerPath = "Save the generated file in the specified directory name"; // Since there is basically no concurrency in downloading Excel files on our project, naming files only in the year, month, day, hour, minute and second can avoid the problem of generating the same file name files. string fileSaveName = "Downloaded file name_" + ("yyyyMMddHHmmss") + ".xls"; string rootDirServerPhysicPath = ("~" + rootDirServerPath); if (!(rootDirServerPhysicPath)) { (rootDirServerPhysicPath); } string[] strFiles = (rootDirServerPhysicPath); if ( > 0) { foreach (string strFile in strFiles) { (strFile); } } //The following is to save the file to the specified directory string userFailedSummaryFileSavePath = rootDirServerPhysicPath + "/" + fileSaveName; if ((userFailedSummaryFileSavePath)) { (userFailedSummaryFileSavePath); } (userFailedSummaryFileSavePath, contentBytes); //Assemble the full path to the file to be downloaded. fileglobal = rootDirServerPath + "/" + fileSaveName; } catch (Exception ex) { = ; = (); return Json(result); } = ; = "Downloading, please wait..."; = fileglobal; return Json(result); }
After completing the operation of generating Excel, make asynchronous calls on the page.
$("#export-excel").click(function (e) { (); $.post("Controller/", $("#Form1").serialize(), function (data) { (, 1.5, , function () { if ( == 1) { (); } else { //Error operation } }); }); });
The above is all the operations in our project about Excel generation to download.
There are fewer considerations and simpler writing.
If you have any good ideas, you can leave a message. I will definitely learn and practice it before sharing it.
Thank you so much.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.