Asp.net MVC is used to generate and download Excel files. asp. netmvc
The example in this article shows you how to generate an Excel file and download the specific code in Asp.net MVC for your reference. The specific content is as follows:
To meet project requirements, you need to export the Excel file with the specified condition. It was finally achieved after a flip.
Paste the code to share it.
(Directly share the code of a helper class in our project)
Our project uses the Asp. Net MVC4.0 mode.
Each ActionResult will inevitably return a View or Json (the parameters in View or Json are of the object type)
Therefore, we need a public class to define the Operation's "success or failure" status or return operation messages in a unified manner, and is conducive to the use of jquery $. get (), $. the uniformity of parameters returned when post () is received.
The following is the StatusMessageData class. (Of course, if you only want to export an Excel file, this class does not need to be defined .)
/// <Summary> /// auxiliary transmission of StatusMessage data /// </summary> [Serializable] public sealed class StatusMessageData {private StatusMessageType messageType; /// <summary> /// Message Type prompt /// </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> /// Message Type prompt /// </summary> public enum StatusMessageType {/// <summary> /// success // </summary> Success = 1, /// <summary> // Error // </summary> Error =-1, /// <summary> /// message // </summary> Hint = 0, /// <summary> /// reminder to log on /// </summary> Login = 5, /// <summary> /// prompt for 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 be downloaded"; return Json (result);} string fileglobal = ""; // organize the Excel table StringBuilder sb = new StringBuilder (400); sb. append ("<table cellspacing = '0' rules = 'all' bord Er = '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>"); // write the file byte [] contentBytes = Encoding in UTF8 format. UTF8.GetBytes (sb. toString (); string rootDirServerPath = "Save the generated file to the specified directory name"; // because the Excel files downloaded from our project are basically not concurrent, therefore, naming a file by year, month, day, minute, 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) ;}}// save the file to the specified directory string userFailedSummaryFileSavePath = rootDirServerPhysicPath + "/" + fileSaveName; if (System. IO. file. exists (userFail EdSummaryFileSavePath) {System. IO. File. Delete (userFailedSummaryFileSavePath);} System. IO. File. WriteAllBytes (bytes, 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 the Excel file is generated, call it 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 {// incorrect operation }});});});
The above are all the operations for generating and downloading Excel files in our project.
There are few considerations, and the write process is relatively simple.
If you have any good ideas, you can leave a message. I will certainly learn and practice it before sharing it.
Thank you very much.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.