C# 如何在ASP.NET MVC 5中将HTML表格从局部视图导出到excel

C# 如何在ASP.NET MVC 5中将HTML表格从局部视图导出到excel,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我花了几个小时在互联网上搜索,但似乎没有人有最新的答案。我在局部视图中设置了一个简单的表,希望导出html表中的数据,而不是从数据库中导出。我也没有选择使用任何插件。我愿意通过JavaScript/Jquery来实现这一点,但我对MVC还相当陌生,我已经在互联网上用尽了其他解决方案 通讯录摘要(部分视图): <table class="table table-bordered table-responsive table-striped" id="tblAddressBook">

我花了几个小时在互联网上搜索,但似乎没有人有最新的答案。我在局部视图中设置了一个简单的表,希望导出html表中的数据,而不是从数据库中导出。我也没有选择使用任何插件。我愿意通过JavaScript/Jquery来实现这一点,但我对MVC还相当陌生,我已经在互联网上用尽了其他解决方案

通讯录摘要(部分视图)

<table class="table table-bordered table-responsive table-striped" id="tblAddressBook">
    <thead>
        <tr>
            <th> @Html.DisplayNameFor(model => model.Name)</th>
            <th> @Html.DisplayNameFor(model => model.Address)</th>
         <tr>
     </thead>
     <tbody>
     @foreach (var item in Model)
        {
        <td class="text-right">@Html.DisplayFor(modelItem => item.Name)</td>
        <td class="text-right">@Html.DisplayFor(modelItem => item.Address)</td>
     }
     </tbody>
     <tfoot>
        <td class="text-right>Model.Sum(model => model.TotalPeople))</td>
        <td class="text-right>Model.Sum(model => model.Addresses))</td>
     </tfoot>

就我个人而言,我会这样做。我将使用JQuery通过以下方式从表中收集数据:

var tableData = {}
$('#tblAddressBook > tbody  > tr').each(function() {...add each row's columns to tableData...});
然后对MVC控制器方法进行AJAX调用。请看这里:

现在数据在控制器方法中,您可以继续使用数据创建excel文件。如果可以的话,我可能会选择.csv文件,而不是.xls文件,因为您很可能需要第三方库来导出到.xls文件

编辑:或者,您可以跳过jquery并将表的模型直接传递给控制器,请参见此处:

如果“通讯簿摘要”(PartialView)仅包含表,则更改代码:-

public ActionResult Export() {
    Response.ContentType = "application/x-msexcel"; 
    Response.AddHeader("Content-Disposition", "attachment;filename=ExcelFile.xls");
    return View();
}
致:-


如果您不能使用任何插件,那么除了使用MicrosoftOpenXMLSDK,您几乎没有其他选择(因为在服务器上使用互操作是您应该不惜一切代价避免的事情)。这将是一条艰难的道路,因为很多代码需要很长时间才能编写并消除bug。或者您可以使用像EPPlus这样的库,并在几分钟内完成它hours@AlexanderDerck我可以花上几个小时,但我知道除了使用MicrosoftOpenXMLSDK之外,还有其他方法可以做到这一点。我见过webforms中的实现,但对于MVC来说没有什么真正有用的
var tableData = {}
$('#tblAddressBook > tbody  > tr').each(function() {...add each row's columns to tableData...});
public ActionResult Export() {
    Response.ContentType = "application/x-msexcel"; 
    Response.AddHeader("Content-Disposition", "attachment;filename=ExcelFile.xls");
    return View();
}
public ActionResult Export()
{
    Response.ContentType = "application/x-msexcel"; 
    Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
    return PartialView("Address_Book_Partial_View_FileName_Here_Without_Extension");
}