Download Excel file via AJAX MVC

后端 未结 14 2004
说谎
说谎 2020-11-22 02:30

I have a large(ish) form in MVC.

I need to be able to generate an excel file containing data from a subset of that form.

The tricky bit is that this shouldn

14条回答
  •  面向向阳花
    2020-11-22 03:15

    I was recently able to accomplish this in MVC (although there was no need to use AJAX) without creating a physical file and thought I'd share my code:

    Super simple JavaScript function (datatables.net button click triggers this):

    function getWinnersExcel(drawingId) {
        window.location = "/drawing/drawingwinnersexcel?drawingid=" + drawingId;
    }
    

    C# Controller code:

        public FileResult DrawingWinnersExcel(int drawingId)
        {
            MemoryStream stream = new MemoryStream(); // cleaned up automatically by MVC
            List winnerList = DrawingDataAccess.GetWinners(drawingId); // simple entity framework-based data retrieval
            ExportHelper.GetWinnersAsExcelMemoryStream(stream, winnerList, drawingId);
    
            string suggestedFilename = string.Format("Drawing_{0}_Winners.xlsx", drawingId);
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", suggestedFilename);
        }
    

    In the ExportHelper class I do use a 3rd party tool (GemBox.Spreadsheet) to generate the Excel file and it has a Save to Stream option. That being said, there are a number of ways to create Excel files that can easily be written to a memory stream.

    public static class ExportHelper
    {
        internal static void GetWinnersAsExcelMemoryStream(MemoryStream stream, List winnerList, int drawingId)
        {
    
            ExcelFile ef = new ExcelFile();
    
            // lots of excel worksheet building/formatting code here ...
    
            ef.SaveXlsx(stream);
            stream.Position = 0; // reset for future read
    
         }
    }
    

    In IE, Chrome, and Firefox, the browser prompts to download the file and no actual navigation occurs.

提交回复
热议问题