jquery 如何使用ASP.NET MVC 5将数据导出到Excel而不重新加载页面?

kxe2p93d  于 2022-11-29  发布在  jQuery
关注(0)|答案(2)|浏览(152)

将数据导出到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>
yrefmtwq

yrefmtwq1#

您可以使用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);
       }
4ioopgfo

4ioopgfo2#

通过$.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);
 }

相关问题