将数据导出到 Excel 的过程正在运行。但我不需要重新加载页面。当我尝试按“将数据导出到 Excel”时,页面正在重新加载。如何避免这种情况?请帮忙。谢谢你。
C#:
public ActionResult Export(int id) {
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add(System.Reflection.Missing.Value);
Excel.Worksheet worksheet = workbook.ActiveSheet;
var export = _context.Employees.Where(x => x.Id == id)ToList();
worksheet.Cells[1, 1] = "Name";
worksheet.Cells[1, 2] = "Age";
worksheet.Cells[1, 3] = "Position";
worksheet.Cells[1, 4] = "Address";
worksheet.Cells[1, 5] = "Contact";
foreach (var e in export)
{
worksheet.Cells[row, 1] = e.Name;
worksheet.Cells[row, 2] = e.Age;
worksheet.Cells[row, 3] = e.Position;
worksheet.Cells[row, 4] = e.Address;
worksheet.Cells[row, 5] = e.Contact;
row++;
}
workbook.SaveAs(@"C:\Excel\sample.xls");
workbook.Close();
Marshal.ReleaseComObject(workbook);
application.Quit();
Marshal.FinalReleaseComObject(application);
return View();
}
阿贾克斯:
<script>
$(document).ready(function() {
$(".js-export").click(function(e) {
var link = $(e.target);
$.ajax({
url: "/home/export/" + link.attr("data-export-id"),
method: "GET"
})
});
});
</script>
活动:
<a href="#" class="js-export btn btn-danger btn-xs" data-export-id="@item.Id">Export to Excel</a>
您可以使用 JsonResult 代替 ActionResult,并且只能返回 excel 文件的 url :-
$.ajax({
type: 'GET',
url: "/home/export/" + link.attr("data-export-id"),
dataType: 'json',
success: function (data) {
console.log(data.ExcelUrl);
}
});
您在控制器中的代码:-
public JsonResult Export(int id)
{
//Exel generation code here showing in your post.
return Json(new { ExcelUrl = "New Excel URL path" }, JsonRequestBehavior.AllowGet);
}
通过
$.ajax
调用操作并在操作中返回 FileResult
:
public FileResult Export(int id)
{
//.........your file creation logic goes here ....//
byte[] fileBytes = File.ReadAllBytes(filePath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}