Search code examples
asp.net-mvc-3downloadfilecontentresultfileresult

Downloading excel file in asp.net mvc


What I'm trying to implement is giving the users the ability to export the grid data to an excel file and download it, with the help of a file save dialog.

Here's how I have coded it right now -

In Javascript -

$.post("/irn/Identifier/Download", { "columnValues": columnValues });

In the Identifier controllers Download action -

public FileResult Download(string columnValues)
{
    DTData headlineRows = (DTData)Newtonsoft.Json.JsonConvert.DeserializeObject(columnValues, typeof(DTData));
    var e = new Services.DownloadToExcel();
    return File(e.WriteData(headlineRows), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "testfile.xlsx");
}

In the DownloadToExcel class, inside the WriteData function I have -

//Here, I'm using the EPPlus library to write the column data to an excel file and then i'm returning the data as a byte array -

//Some code that writes the data
return packages.GetAsByteArray();

When I run this code, I expect to see a File Save Dialog in the browser, but nothing happens. There aren't any errors on the C# or JavaScript side. Can anyone tell me what i could be doing wrong?


Solution

  • I solved this but forgot to update here -

    This worked -

    Inside my class -

    private const string MimeType = "application/vnd.openxmlformats- 
    officedocument.spreadsheetml.sheet";
    
    private ExcelPackage package = new ExcelPackage();
    
    private FileContentResult excelFile;
    
    Write data using EPPlus
    
     ...
    
     ...
    
     ...
    
    excelFile = File(package.GetAsByteArray(), MimeType, FileName);
    
     return excelFile;