将 HTML 表格导出到 Excel

发布于 2024-08-20 17:09:54 字数 3510 浏览 6 评论 0原文

我在 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);
        }

I have HTML table on the ASP.NET MVC View page. Now I have to export this table to Excel.

(1) I have used partial view (Inquiries.ascx) to display the table data from database (using LINQ to Entity)
(2) I also have used UITableFilter plugin to filter the records (Ex: http://gregweber.info/projects/demo/flavorzoom.html )

(3) At any point of time, I have to filter the visible records to Excel.

Appreciate your responses.

Thanks

Rita

Here is my View:

<%@ 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>

Strongly Typed Partial view user control (Inquiries.ascx) to generate table:

<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>

Here is my Controller code to load the Inquiries partial view:

[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);
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

喵星人汪星人 2024-08-27 17:09:54

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

下面是一个实现:

  1. 在页面中添加一个常规 html 输入按钮和一个 .NET HiddenField
  2. 将 onclick 事件添加到名为“Export”的按钮
  3. 创建一个 javascript 函数 Export,它将 table2CSV() 的返回值存储到隐藏字段中,并回帖。
  4. 服务器接收hiddenfield post数据(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();  
    }  
}

Try the jQuery plugin: table2csv. Use the argument, delivery:'value', to return the csv as a string.

Here is an implementation:

  1. Add a regular html input button and a .NET HiddenField to the page
  2. Add an onclick event to that button called "Export"
  3. Create a javascript function, Export, that stores the return value of table2CSV() into the hidden field, and posts back.
  4. The server receives the hiddenfield post data (the csv as a string)
  5. The server outputs the string to the browser as a csv file

.

// 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();  
    }  
}
没有心的人 2024-08-27 17:09:54

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

download components: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"}]);
};

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文