0

I'm using EPPLUS to generate an Excel File. I have code to save it to the server but I can't figure out how to allow the client to download the Excel sheet.The user clicks the button and it downloads to where ever they have it set in their browser. I found the client download code here that I can't get to work...It's not throwing an error in Firebug or Fiddler

JQuery

$('#ExcelExport').on('click', function () {
    $.post("/Reports/ExportToExcel", function (data) {
        alert("The Export was Succussful");
    })
    .fail(function () {
        alert("The Export has Failed");
 });

C#

public ActionResult ExportToExcel()
{

    using (ExcelPackage package = new ExcelPackage())
    {
        // Get Data
        var excelData = _repository.ExcelData();

        //Basic Info
        package.Workbook.Properties.Author = "MEO System";
        package.Workbook.Properties.Title = "PendingMEOs";

        //Excel worksheet
        package.Workbook.Worksheets.Add("Pending MEOs");
        ExcelWorksheet ws = package.Workbook.Worksheets[1]; // 1 is the position of the worksheet
        ws.Name = "Pending MEOs";

        //adds the data to the excel sheet and formats the data
        ws.Cells.LoadFromCollection(excelData, true, OfficeOpenXml.Table.TableStyles.Medium6);

        //sets the cell width to fit the contents
        ws.Cells["A1:L" + excelData.Count()].AutoFitColumns();

        // Save the Excel file
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;  filename=PendingMEOS.xlsx");
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.BinaryWrite(package.GetAsByteArray());
        Response.End();
    }

    return Json(new { success = true });
}

Save Code to the server, works but not what I want

string path = "C:\\PendingMEOS.xlsx";

Byte[] bin = package.GetAsByteArray();
System.IO.File.WriteAllBytes(path, bin);
joetinger
  • 2,589
  • 6
  • 29
  • 43

1 Answers1

1

The problem is you are writing directly to the Response stream but then return a Json result.

Take a look at MVC Controller Using Response Stream

Community
  • 1
  • 1
Vince
  • 620
  • 1
  • 5
  • 9
  • After adding `return new EmptyResult();` It says it is successful but the browser doesn't notify you of the download and I am unable to find it so I don't think it is actually downloading anywhere. Am I missing some code to get it to download? – joetinger Nov 05 '14 at 19:58
  • 1
    Your post success handler only alert the success message and didn't do anything with the data. If your intention is just to download the file, try having a link directly to /Reports/ExportToExcel. – Vince Nov 05 '14 at 20:08