将数据导出到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();
}
AJAX :
<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>
2条答案
按热度按时间yrefmtwq1#
您可以使用JsonResult代替ActionResult,并且只能返回Excel文件的url:-
您在控制器中的代码:-
4ioopgfo2#
通过
$.ajax
调用操作并在操作中返回FileResult
: