Search code examples
jqueryajaxasp.net-core-mvc

Ajax call for downloading data in excel is not working


I have written code in .NET Core to download data in Excel by making a call to the action method manually.

But the same code fails to work when we give a call to same action using jQuery Ajax.

I tried looking at few article online but no success.

My action is simple where I am passing this months parameter into the controller and downloading the data for this month. As mentioned above the manual call works, but the Ajax call does not download the file.

Controller action method

public IActionResult Tasksheet()
{
    using var workbook = new XLWorkbook();
    var worksheet = workbook.Worksheets.Add("DefectEfforts");
    
    var currentRow = 1;
 
    var startDate = DateTime.Now.Date;
    startDate = new DateTime(startDate.Year, startDate.Month, 1);

    var endDate = startDate.AddMonths(1).AddSeconds(-1);
    var model = db.DefectEfforts.Where(x => x.ActualStartDate >= startDate && x.ActualStartDate < endDate).ToList();

    worksheet.Cell(currentRow, 1).Value = "Project";
    worksheet.Cell(currentRow, 2).Value = "Task";
    worksheet.Cell(currentRow, 3).Value = "Status";
    worksheet.Cell(currentRow, 4).Value = "Responsible";

    foreach (var user in model)
    {
        currentRow++;
        worksheet.Cell(currentRow, 2).Value = user.ProjectSubtask;
        worksheet.Cell(currentRow, 3).Value = user.Effortstatus;
        worksheet.Cell(currentRow, 4).Value = user.UserName;
        worksheet.Cell(currentRow, 1).Value = user.Projectname;
    }
    
    using var stream = new MemoryStream();
    workbook.SaveAs(stream);
    var content = stream.ToArray();

    return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "MontlyTasks.xlsx");
}

Ajax call

$('#extractData').click(function (e) {
    e.preventDefault()

    //var pds = $('#preDefinedSelect :selected').val()

    //alert(pds)

    $.ajax({
        type: "POST",
        url: "/Task/Tasksheet",
        success: function (result) {
            alert("Export generated")
        }, error: function() {
            alert("Failed to export data")
        }

    })
})

Controller generated value

generated value

Any suggestions are much appreciated.


Solution

  • My action is simple where I am passing this months parameter into the controller and downloading the data for this month. As mentioned above the manual call works, but the Ajax call does not download the file

    Based on your shared code snippet and description you care getting the unexpected result because of your ajax function as you did not decide anything in success.

    After executing the Tasksheet method, the FileContentResult is returned to the Ajax success function, but there's nothing inside.

    In order to download your excel you need one additional download method which should be called, inside ajax success funtion using window.location to redirect to the DownloadExcel action in controller.

    Let's have a look in practice:

    public virtual ActionResult DownloadExcel()
    {
        TempData["file"] = "This is sample";
    
       
        string fileContent = TempData["file"] as string;
        byte[] content = Encoding.UTF8.GetBytes(fileContent);
    
        // Return the file with the appropriate content type and filename
        return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "MonthlyTasks.xlsx");
    
    }
    

    Note: In order to demonstrate the demo I just used sample content, replace the content with your excel data.

    Ajax:

    <button type="button" name="submitButton" value="Edit" class="btn btn-primary"
            onclick="GetAjaxResponse()">
        Submit Request
    </button>
    
    
    
    @section scripts {
        <script>
            function GetAjaxResponse() {
                $.ajax({
                    type: "POST",
                    url: "/NullModel/Tasksheet",
                    success: function (result) {
                        window.location = '/ControllerName/DownloadExcel';
                    }, error: function () {
                        alert("Failed to export data")
                    }
    
                })
    
            }
        </script>
    }
    

    Ouput:

    enter image description here enter image description here