允许客户端下载Excel文件

时间:2014-11-05 18:46:42

标签: c# epplus

我使用EPPLUS生成Excel文件。我有代码将其保存到服务器但我无法弄清楚如何允许客户端下载Excel工作表。用户单击该按钮并将其下载到他们在浏览器中设置的位置。我找到了我无法开始工作的客户端下载代码here ...它没有在Firebug或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 });
}

将代码保存到服务器,但无法正常工作

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

Byte[] bin = package.GetAsByteArray();
System.IO.File.WriteAllBytes(path, bin);

1 个答案:

答案 0 :(得分:1)

问题是您是直接写入Response流但是然后返回Json结果。

查看MVC Controller Using Response Stream