【问题标题】:Export HTML Table to Excel将 HTML 表格导出到 Excel
【发布时间】:2010-02-04 01:00:56
【问题描述】:

我在 ASP.NET MVC 视图页面上有 HTML 表格。现在我必须将此表导出到 Excel。

(1) 我使用局部视图 (Inquiries.ascx) 显示数据库中的表数据(使用 LINQ to Entity) (2) 我也使用了 UITableFilter 插件来过滤记录(例如:http://gregweber.info/projects/demo/flavorzoom.html

(3) 在任何时候,我都必须将可见记录过滤到 Excel。

感谢您的回复。

谢谢

丽塔

这是我的观点:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mvc.Master" Inherits="System.Web.Mvc.ViewPage" %>


<asp:Content ID="Content2" ContentPlaceHolderID="cphHead" runat="server">
<script src="../../Scripts/jquery.tablesorter.js" type="text/javascript"></script>
     <script src="../../Scripts/jquery.uitablefilter.js" type="text/javascript"></script>

<script type="text/javascript">
 //Load Partial View
$('#MyInquiries').load('/Home/Inquiries');

// To Apply Filter Expression using uiTableFilter plugin
            $("#searchName").keyup(function() {
                $.uiTableFilter($("#tblRefRequests"), this.value);
                $("#tblRefRequests").tablesorter({ widthFixed: true, widgets: ['zebra'] });
            });


//Export the HTML table contents to Excel
      $('#export').click(function() {
//Code goes here

});
</script>
</asp:Content>

//Main Content
<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" runat="server">
<h2 class="pageName">View All Inquiries</h2>
<input type="submit" value="Export to Excel" id="export" />
<div id='MyInquiries'></div>
</asp:Content>

强类型分部视图用户控件(Inquiries.ascx)生成表:

<table>
    <tr><td valign ="middle">Filter Expression: <%= Html.TextBox("searchName")%></td></tr>
    </table>
    <table id="tblRefRequests" >
    <thead>
        <tr>
            <th>Tx_ID</th>
            <th>TX Date</th>
            <th>Name</th>
            <th>Email Address </th>
            <th>Products</th>
            <th>Document Name</th>
        </tr>
</thead>

<tbody>
    <% foreach (var item in Model) { %>
        <tr>
            <td visible =false><%= item.RequestID %></td>
            <td><%= String.Format("{0:d}", item.RequestDate) %></td>
            <td><%= item.CustomerName %></td>
            <td><%= Html.Encode(item.Email) %></td>
            <td><%= item.ProductName %></td>
            <td><%= Html.Encode(item.DocDescription)%></td>
        </tr>
    <% } %>
</tbody>
    </table>

这是我加载查询部分视图的控制器代码:

[HttpGet]
        public PartialViewResult Inquiries()
        {
var model = from i in myEntity.Inquiries
  where i.User_Id == 5
                        orderby i.TX_Id descending
                        select new {
                            RequestID = i.TX_Id,
                            CustomerName = i.CustomerMaster.FirstName,
                            RequestDate = i.RequestDate,
                            Email = i.CustomerMaster.MS_Id,
                            DocDescription = i.Document.Description,
                            ProductName = i.Product.Name
                        };
            return PartialView(model);
        }

【问题讨论】:

    标签: asp.net jquery asp.net-mvc jquery-ui export-to-excel


    【解决方案1】:

    试试 jQuery 插件:table2csv。使用参数 delivery:'value' 将 csv 作为字符串返回。

    这是一个实现:

    1. 向页面添加常规 html 输入按钮和 .NET HiddenField
    2. 为该按钮添加一个名为“导出”的 onclick 事件
    3. 创建一个 javascript 函数 Export,它将 table2CSV() 的返回值存储到隐藏字段中,然后回发。
    4. 服务器接收隐藏字段发布数据(csv作为字符串)
    5. 服务器将字符串作为csv文件输出到浏览器

    .

    // javascript  
    function Export()  
    {    
        $('#yourHiddenFieldId').val() = $('#yourTable').table2CSV({delivery:'value'});  
        __doPostBack('#yourExportBtnId', '');  
    }
    
    // c#  
    if(Page.IsPostBack)  
    {
        if(!String.IsNullOrEmpty(Request.Form[yourHiddenField.UniqueId]))  
        {  
            Response.Clear();  
            Response.ContentType = "text/csv";  
            Response.AddHeader("Content-Disposition", "attachment; filename=TheReport.csv");  
            Response.Flush();  
            Response.Write(Request.Form[yourHiddenField.UniqueID]);  
            Response.End();  
        }  
    }
    

    【讨论】:

    • 我试过了。它以字符串形式出现在新窗口中。但我想要在 Excel 文件中。
    • 我添加了示例代码。看看这个。而且我不知道您对导出 Excel 的态度如何。那完全是另外一头野兽。我建议导出 CSV。导出 CSV 文件比导出 Excel 文件更容易、更快、更轻量级和更优雅。您可以将其记为“CSV for Excel”。我就是这么做的。
    【解决方案2】:

    下载组件:npm install table-to-excel

    https://github.com/ecofe/tabletoexcel

    var tableToExcel=new TableToExcel();
    document.getElementById('button1').onclick=function(){
    
        tableToExcel.render("table");
    
    };
    document.getElementById('button2').onclick=function(){
        var arr=[
            ['LastName','Sales','Country','Quarter'],
            ['Smith','23','UK','Qtr 3'],
            ['Johnson','14808','USA','Qtr 4']
        ]
        tableToExcel.render(arr,[{text:"create",bg:"#000",color:"#fff"},{text:"createcreate",bg:"#ddd",color:"#fff"}]);
    };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-15
      • 2018-06-24
      • 2023-03-21
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2023-03-27
      • 2014-06-20
      相关资源
      最近更新 更多