我有一個使用EPPlus在服務器上生成的Excel文件,該文件是正確創建的,並且使用window.location在本地計算機上工作正常,但在部署時不執行任何操作到服務器。我試圖通過MVC控制器返回一個FileStreamResult,但我認爲它不工作。我使用ajax調用來訪問控制器方法,但在方法運行時無法輸入.done。如何使用EPPlus和MVC從服務器下載.xslx文件
我一直在尋找ASP.NET MVC EPPlus Download Excel File爲我的C#參考。
腳本
function exportToExcel() {
var batchName = $("#batchDateSelect option:selected").text();
var bID = $("#batchDateSelect").val();
var params = {
BatchID: bID,
BatchName: batchName
};
$.post(path + "Export/ExportToExcel", params)
.done(function (Data, textStatus, jqXHR) {
var fileName = "";
////window.location = path + "ExportFiles/"+fileName;
});
}
控制器
public ActionResult ExportToExcel(int BatchID,string BatchName)
{
FileStreamResult FSR = DataAccess.ExportUtility.CreateExcelFile(BatchID, BatchName);
return FSR;
}
EPPlus方法
public static FileStreamResult CreateExcelFile(int batchid,string batchName)
{
string fileName = batchName + " Reason_Code_Export.xlsx";
var serverPath = HttpContext.Current.Server.MapPath("~/ExportFiles/");
DirectoryInfo outputDir = new DirectoryInfo(serverPath);
FileInfo newfile = new FileInfo(outputDir.FullName + fileName);
if (newfile.Exists)
{
newfile.Delete();
newfile = new FileInfo(outputDir.FullName + fileName);
}
Dictionary<string,int> MAData = PolicyDataAccess.GetMatchActionData(batchid);
MemoryStream MS = new MemoryStream();
using (ExcelPackage package = new ExcelPackage(newfile))
{
..........
........
package.SaveAs(MS);
}
MS.Position = 0;
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
FileStreamResult FSR = new FileStreamResult(MS, contentType);
FSR.FileDownloadName = fileName;
return FSR;
}
什麼是獲取該文件的最簡單的方法?
謝謝,這有助於解決與「eprlus」編輯模板時「損壞」文件相關的問題 – blfuentes