如何使用Ajax方法下载excel文件-这里我的文件是在Temp文件夹中下载的,而不是在浏览器中下载的



我想下载一个excel文件。我正在使用ajax方法获取文件,但它对我不起作用。我的文件被下载到一个临时文件夹中,但它没有在浏览器中下载。

c#和jquery

jquery

//Exporting errors to excel file
function ExcportErrorListToExcel() {
debugger;
$.ajax({
url: 'Import/ExportErrorToExcel',
type: 'GET',
data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
//contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
success: function (returnValue) {
debugger;       
window.location = '/Import/ExportErrorToExcel?file=' + returnValue.filename;
//alert('success');
}
});
}

控制器

#region ExportErrorToExcel        
public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
{
UA patsUA = Session["PaTSUA"] as UA;
DataTable dataTable = null;
dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);
string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString() + ".xlsx");

_dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);
FileInfo fileInfo = new FileInfo(tempPath);
if (fileInfo.Exists)
{
Response.Clear();
byte[] excelBytes = System.IO.File.ReadAllBytes(tempPath);
MemoryStream memoryStream = new MemoryStream(excelBytes);
Response.ContentType= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=ErrorList.xlsx");
Response.Buffer = true;
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
//System.IO.File.Delete(tempPath);
}
//var errorRowList = (from e in dataTable.AsEnumerable()
//                             where e.Field<string>("DataError").ToString() != ""
//                             select e).ToList();
return File(tempPath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(tempPath));
//return Json(new { Status = "OK", Records = tempPath, contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
}
#endregion ExportErrorToExcel

试试这个

//Exporting errors to excel file
function ExcportErrorListToExcel() {
debugger;
$.ajax({
url: 'Import/ExportErrorToExcel',
type: 'GET',
data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
//contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
success: function (returnValue) {
debugger;  
var link=document.createElement('a');
document.body.appendChild(link);
link.href="/Temp/" + returnValue.filename;
link.click();
link.remove();
}
});
}

这可以简单地通过将控制器函数一分为二来完成。第一个功能将将文件保存在临时文件夹中,并将文件名传递给jqueryAjax函数,在其成功部分,它将重定向到控制器中的第二个函数。在这里我们将下载文件

这是Ajax

function ExportErrorListToExcel() {
debugger;
$.ajax({
url: "Import/ExportErrorToExcel",
type: "POST",
data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
success: function (responsetext, status, xhr) {
debugger;
window.location = 'Import/DownloadErrorData?fname=' + responsetext.FileName;
}
});
// $('#ExcelExportForm').submit();
}

以下是控制器功能,文件保存到临时文件夹中

#region ExportErrorToExcel
//This function will return the file name to script
public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
{
UA patsUA = Session["PaTSUA"] as UA;
DataTable dataTable = null;
dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);
string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString()+ ".xlsx");            
_dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);
string fname = Path.GetFileName(tempPath);
return Json(new { Result = "true", Message = "Success", FileName = fname,Entity=entityvalue });
}
#endregion ExportErrorToExcel

这是控制器的第二个功能,用于从Temp文件夹下载文件

#region DownloadErrorData
//In this function recieve the filename and will download it from the location
public ActionResult DownloadErrorData(string fname)
{
string fileName ="ErrorList.xlsx";
string filePath= Path.Combine(Server.MapPath("~/Temp/" + fname));
try
{
string[] allFiles = Directory.GetFiles(Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar);
foreach (string file in allFiles)
{
FileInfo fileinfo = new FileInfo(file);
if (fileinfo.CreationTime < DateTime.Now.AddDays(-2))
{
fileinfo.Delete();
}
}
}
catch (Exception ex)
{
throw ex;
}
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//web content type of .xlsx files
return File(filePath, contentType, fileName);
}
#endregion DownloadErrorData

希望这对某人有所帮助:)

最新更新