Example of an Excel file generated using Ajax and downloaded

Source: Internet
Author: User
The Excel file generated using Ajax has not been written for a long time and has been downloaded from the instance. Today, I will share my article on how to use ASP. net mvc uses Ajax to generate files. The following is my personal experience:

Everyone should know that in ASP. net mvc, if the controller is used after Ajax expires, a json object can be returned, but the object cannot be directly returned (unless the interface is refreshed, so if you want to use Ajax to generate a file and download it, you only need to save the generated file to the server first, then, the file path is returned in JSON format before it can be written down. Of course, it is stored in temporary mode, therefore, after the download, the corresponding file needs to be deleted immediately.

The following is an example of how to generate an Excel file by using an animation (I will omit the specific steps for generating an Excel file, which is not the focus of this article ):

1. Create an Action to generate an Excel file.

[HttpPost] public JsonResult ExportExcel () {DataTable dt = DataService. getData (); var fileName = "Excel _" + DateTime. now. toString ("yyyyMMddHHmm") + ". xls "; // Save the generated file to the duration of the server. string fullPath = Path. combine (Server. mapPath ("~ /Temp "), fileName); using (var exportData = new MemoryStream () {// how to generate an Excel file, I am using NPOI Utility for Excel operations here. writeDataTableToExcel (dt ,". xls ", exportData); FileStream file = new FileStream (fullPath, FileMode. create, FileAccess. write); exportData. writeTo (file); file. close ();} var errorMessage = "you can return the errors in here! "; // Return the generated file name return Json (new {fileName = fileName, errorMessage = ""});}

2. Create the Action used by the producer

[HttpGet] [DeleteFileAttribute] // Action Filter. After the Download is complete, the file is automatically deleted. After the Download, the public ActionResult Download (string file) is obtained) {// The file string fullPath = Path corresponding to the file under the file category when the server crashes. combine (Server. mapPath ("~ /Temp "), file); // return the object, which uses Excel, so the file header uses" application/vnd. ms-excel "return File (fullPath," application/vnd. ms-excel ", file );}

3. to automatically delete files after the download, create an Action Filter.

Public class DeleteFileAttribute: ActionFilterAttribute {public override void OnResultExecuted (ResultExecutedContext filterContext) {filterContext. httpContext. response. flush (); // convert the filter context into a file for specific operations and extract the path string filePath = (filterContext. result as FilePathResult ). fileName; // after a file path exists, you can directly delete the related file System. IO. file. delete (filePath );}}

4. Add the Ajax Token Generation in the previous example:

// Here I use blockUI for loading... $. blockUI ({message: 'Please wait a moment... '}); $. ajax ({type: "POST", url: '@ Url. action ("ExportExcel", "YourController") ', // use the corresponding controller/action contentType: "application/json; charset = UTF-8", dataType: "json ",}). done (function (data) {// console. log (data. result); $. unblockUI (); // receives the returned file path. This file has been saved to the server if (data. fileName! = "") {// The window is used by the cursor. location. href directly jumps to the next action to perform the window operation in the next action file. location. href = "@ Url. routeUrl (new {Controller = "YourController", Action = "Download "})/? File = "+ data. fileName ;}});

5. Complete!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.