本文介绍了允许客户端下载Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用EPPLUS生成Excel文件.我有将其保存到服务器的代码,但我不知道如何允许客户端下载Excel工作表.用户单击该按钮,它将下载到他们在浏览器中设置的位置.我在此处找到了我无法使用的客户端下载代码...这不是抛出Firebug或Fiddler中的错误
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 });
}
将代码保存到服务器,可以正常运行,但不满足我的要求
string path = "C:\\PendingMEOS.xlsx";
Byte[] bin = package.GetAsByteArray();
System.IO.File.WriteAllBytes(path, bin);
推荐答案
问题是您正在直接写入Response流,但是随后返回Json结果.
The problem is you are writing directly to the Response stream but then return a Json result.
这篇关于允许客户端下载Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!