导出HTML表到Excel [英] Export HTML Table to Excel

查看:91
本文介绍了导出HTML表到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ASP.NET MVC查看页面上的HTML表格。现在我有这个表导出到Excel中。

(1)我用局部视图(Inquiries.ascx)来显示从数据库中的表数据(使用LINQ到实体)
(2)我也用过UITableFilter插件过滤记录(例如:<一href=\"http://gregweber.info/projects/demo/flavorzoom.html\">http://gregweber.info/projects/demo/flavorzoom.html )

(3)在任何时候,我都可见记录筛选到Excel中。

鸭preciate你的反应。

感谢

丽塔

下面是我的看法:

 &LT;%@页标题=LANGUAGE =C#的MasterPageFile =〜/查看/共享/ Mvc.Master继承=System.Web.Mvc.ViewPage %GT;
&LT; ASP:内容ID =内容2ContentPlaceHolderID =cphHead=服务器&GT;
&LT;脚本SRC =../../脚本/ jquery.tablesorter.js类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;
     &LT;脚本SRC =../../脚本/ jquery.uitablefilter.js类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;&LT;脚本类型=文/ JavaScript的&GT;
 //加载局部视图
$('#MyInquiries')负载('/主页/咨询');//要使用uiTableFilter插件应用过滤器前pression
            $(#searchName)。KEYUP(函数(){
                $ .uiTableFilter($(#tblRefRequests),THIS.VALUE);
                $(#tblRefRequests)的tablesorter({widthFixed:真,窗口小部件:['斑马']});
            });
//导出HTML表格内容到Excel
      $('#出口')。点击(函数(){
// code到这里});
&LT; / SCRIPT&GT;
&LT; / ASP:内容&GT;//主要内容
&LT; ASP:内容ID =内容1ContentPlaceHolderID =cphContent=服务器&GT;
&LT; H2类=页面名称&gt;查看所有的查询&LT; / H&GT;
&LT;输入类型=提交值=导出到ExcelID =出口/&GT;
&LT; D​​IV ID ='MyInquiries'&GT;&LT; / DIV&GT;
&LT; / ASP:内容&GT;

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

 &LT;表&gt;
    &所述; TR&GT;&下; TD VALIGN =中间的过滤器过滤前pression:其中;%= Html.TextBox(searchName)%&GT;&下; / TD&GT;&下; / TR&GT;
    &LT; /表&gt;
    &LT;表ID =tblRefRequests&GT;
    &LT;&THEAD GT;
        &所述; TR&GT;
            &LT;第i Tx_ID&LT; /第i
            &LT;第i TX日期和LT; /第i
            &LT;第i个姓名和LT; /第i
            &LT;第i个电子邮件地址&LT; /第i
            &LT;第i产品&LT; /第i
            &LT;第i个文档名称与LT; /第i
        &LT; / TR&GT;
&LT; / THEAD&GT;&LT;&TBODY GT;
    &LT;%的foreach(在型号VAR项){%GT;
        &所述; TR&GT;
            &LT; TD可见=假&gt;&LT;%= item.RequestID%GT;&LT; / TD&GT;
            &LT; TD&GT;&LT;%=的String.Format({0:D},item.RequestDate)%GT;&LT; / TD&GT;
            &所述; TD&GT;&下;%= item.CustomerName%GT;&下; / TD&GT;
            &LT; TD&GT;&LT;%= Html.En code(item.Email)%GT;&LT; / TD&GT;
            &所述; TD&GT;&下;%= item.ProductName%GT;&下; / TD&GT;
            &LT; TD&GT;&LT;%= Html.En code(item.DocDescription)%GT;&LT; / TD&GT;
        &LT; / TR&GT;
    &LT;%}%GT;
&LT; / TBODY&GT;
    &LT; /表&gt;

下面是我的控制器code加载查询局部视图:

  [HTTPGET]
        公共PartialViewResult咨询()
        {
在myEntity.Inquiries VAR模型=从我
  其中,i.User_Id == 5
                        排序依据i.TX_Id降
                        选择新{
                            请求ID = i.TX_Id,
                            客户名称= i.CustomerMaster.FirstName,
                            RequestDate = i.RequestDate,
                            电子邮件= i.CustomerMaster.MS_Id,
                            DocDescription = i.Document.Description,
                            产品名称= i.Product.Name
                        };
            返回PartialView(模型);
        }


解决方案

尝试jQuery插件: table2csv 。使用参数,交货:'价值',返回CSV作为一个字符串

下面是一个实现:


  1. 添加一个普通HTML输入按钮和一个.NET HiddenField页面

  2. 添加一个onclick事件到该按钮被称为导出

  3. 创建一个JavaScript函数,出口,存储table2CSV()进入隐藏字段的返回值,会回。

  4. 服务器接收hiddenfield后的数据(CSV作为字符串)

  5. 服务器将输出字符串到浏览器作为一个CSV文件

  //的javascript
功能导出()
{
    $('#yourHiddenFieldId)VAL()= $('#yourTable')table2CSV({交货:'值'});
    __doPostBack('#yourExportBtnId','');
}// C#
如果(Page.IsPostBack)
{
    如果(!String.IsNullOrEmpty(的Request.Form [yourHiddenField.UniqueId]))
    {
        Response.Clear();
        Response.ContentType =TEXT / CSV;
        Response.AddHeader(内容处置,附件;文件名= TheReport.csv);
        Response.Flush();
        回复于(的Request.Form [yourHiddenField.UniqueID]);
        到Response.End();
    }
}

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

解决方案

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

这篇关于导出HTML表到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆