2010-02-04 163 views
5

Tengo tabla HTML en la página ASP.NET MVC View. Ahora tengo que exportar esta tabla a Excel.Exportar tabla HTML a Excel

(1) he utilizado vista parcial (Inquiries.ascx) para visualizar los datos de la tabla de base de datos (usando LINQ a la Entidad) (2) También he utilizado Plugin UITableFilter para filtrar los registros (Ex: http://gregweber.info/projects/demo/flavorzoom.html)

(3) En cualquier momento, tengo que filtrar los registros visibles a Excel.

Valora tus respuestas.

Gracias

Rita

Aquí es mi punto de vista:

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

fuertemente tipado Vista parcial de control de usuario (Inquiries.ascx) para generar la tabla:

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

Aquí es mi código de controlador para cargar la vista parcial de consultas:

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

Respuesta

5

Pruebe el plugin jQuery: table2csv. Use el argumento, entrega: 'valor', para devolver el csv como una cadena.

Aquí es una implementación:

  1. Agregar un botón de entrada regular de HTML y una HiddenField .NET a la página
  2. Añadir un evento onclick a ese botón llamado "Exportar"
  3. crear una función javascript , Exportar, que almacena el valor de retorno de table2CSV() en el campo oculto y publicaciones posteriores.
  4. El servidor recibe los datos enviados HiddenField (el csv como una cadena)
  5. El servidor emite la cadena en el navegador como un archivo csv

. componentes

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

lo intentara. Viene como una cadena en una nueva ventana. Pero quiero eso en el Archivo de Excel. – Rita

+0

Agregué código de ejemplo. Echale un vistazo. Y no sé cómo estás en la exportación de Excel. Esa es una bestia completamente diferente. Sugiero exportar CSV. Es mucho más fácil, más rápido y más liviano y elegante exportar un archivo CSV frente a un archivo Excel. Puede facturarlo como "CSV for Excel". Eso es lo que hago. –

+0

Parece que va a funcionar. Intentaremos ahora n actualizar en breve. – Rita

0

de descarga: NPM instalan mesa-a-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"}]); 
 
};

Cuestiones relacionadas