简体   繁体   中英

Call ActionMethod of a Controller in ASP.NET MVC from Javascript that results in Excel Worksheet saved

I would like to call an ActionMethod of a Controller that returns an Excel Worksheet. I know that I could simply redirect the URL to http://website/Excel/GenerateReport and it would work. But I would like to popup a busy spinner right before the call to controller and close the spinner right after. In the mean time the Controller's ActionMethod would generate Excel Report and return it.

The ActionMethod looks like this:

public ActionResult CreateReport()
    {
        try
        {
            // Opening the Excel template...
            var fs = new FileStream(Server.MapPath(@"~\Content\Excel\Template.xlsx"), FileMode.Open, FileAccess.Read);

            // Getting the complete workbook...
            var templateWorkbook = new XSSFWorkbook(fs);

            // Getting the worksheet by its name...
            //HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");
            var sheet = templateWorkbook.GetSheet("Report");

            // Getting the row... 0 is the first row.
            //HSSFRow dataRow = sheet.GetRow(4);
            var dataRow = sheet.GetRow(4);

            dataRow.CreateCell(0, CellType.Numeric);

            dataRow.GetCell(0).SetCellValue(11.11);

            // Forcing formula recalculation...
            sheet.ForceFormulaRecalculation = true;

            var ms = new MemoryStream();

            // Writing the workbook content to the FileStream...
            templateWorkbook.Write(ms);

            TempData["Message"] = "Excel report created successfully!";

            // Sending the server processed data back to the user computer...
            return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
        }
        catch (Exception ex)
        {
            TempData["Message"] = "Oops! Something went wrong.";

            return RedirectToAction("NPOI");
        }
    }

I tried ajax but not luck...

Here's a general idea what I tried:

            showProgress();

            $.ajax({
                url: ajaxUrl,
                type: "get",
                data: {
                    tmoCode: $("#tmoDropDownList").val(),
                    clientCode: $("#clientDropDownList").val(),
                    productCode: $("#productDropDownList").val(),
                    startDateCode: $("#startDateDropDownList").val(),
                    endDateCode: $("#endDateDropDownList").val()
                },
                success: function (response, textStatus, jqXHR) {
                    alert("Success");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error Creating Excel Report!");
                },
                // callback handler that will be called on completion
                // which means, either on success or error
                complete: function () {
                    hideProgress();
                }
            });

Any idea is appreciated! But please remember that I need to: 1. display the Spinner 2. run the report and return it as excel worksheet 3. hide the Spinner

Thanks in advance!

Check it out - https://github.com/johnculviner/jquery.fileDownload and see a demo - http://jqueryfiledownload.apphb.com/

You can use something like this:

$(function() {
    $(document).on("click", "a.downloadFile", function() {

        showProgress();

        $.fileDownload($(this).prop('href'), {
            successCallback: function(url) {

                hideProgress();
            },
            failCallback: function(responseHtml, url) {

                hideProgress();
            }
        });

        return false; //this is critical to stop the click event which will trigger a normal file download!
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM