将HTML表格导出为Excel

5
我在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>

这是我的控制器代码,用于加载“Inquiries”部分视图:

[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);
        }
2个回答

5
尝试使用jQuery插件:table2csv。使用参数delivery:'value',将CSV作为字符串返回。
以下是实现步骤:
  1. 向页面添加常规HTML输入按钮和.NET HiddenField。
  2. 添加名为“Export”的onclick事件。
  3. 创建一个名为Export的JavaScript函数,将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文件中。 - Rita
我添加了示例代码,请查看。我不知道你对导出Excel有多么执着。那是另一个问题。我建议导出CSV。与导出Excel文件相比,导出CSV文件更容易、更快速、更轻量级和更优雅。你可以将其称为“Excel的CSV格式”。这就是我所做的。 - Bill Paetzke

0

下载组件: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"}]);
};


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接