joetinger
joetinger

Reputation: 2729

Allow Client to Download Excel File

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);

Upvotes: 0

Views: 1903

Answers (1)

Vince
Vince

Reputation: 650

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

Upvotes: 1

Related Questions