Jquery выгрузка в excel

<!DOCTYPE html>

<html>

    <head>

        <title>jQuery table2excel plugin</title>

        <script src=

        </script>

        <script src="jquery.table2excel.js"></script>

    </head>

    <body>

        <h1 style="color:green">GeeksForGeeks</h1>

        <b>jQuery table2excel plugin </b>

        <p></p>

        <table class="table2excel">

            <thead>

                <tr class="noExl">

                <td>

                    Table 1 Header, column 1 (not exported)</td>

                   <td>Table 1 Header, column 2(not exported)

                </td>

              </tr>

                <tr><td>Table 1 Header, column 1 (exported)</td>

               <td>Table 1 Header, column 2 (exported)</td></tr>

            </thead>

            <tbody>

                <tr><td>Row 1, column 1 data of table1</td>

                <td>Row 1 column 2 data of table 1</td></tr>

                <tr><td>Row 2, column 1 data of table1</td>

                <td>Row 2, column 2 dataof table1</td></tr>

            </tbody>

            <tfoot>

                <tr><td colspan="2">This is the footer of table 1.</td></tr>

            </tfoot>

        </table>

        <button class="exportBtnClass">Export to XLS file</button><p></p>

        <table class="table2excel colorClass">

            <thead>

                <tr class="noExl">

                <td>Table 2 Header, column 1 (not exported)</td>

                <td>Table 2 Header, column 1 (not exported)</td></tr>

                <tr><td style="background-color: green;">

    Table 2 Header, column 1 (exported with colors)</td>

             <td>Table 2 Header, column 2 (exported)</td></tr>

            </thead>

            <tbody>

                <tr><td style="background-color: red;">

          Row 1, column 1 data of table2</td>

         <td>Row 1 column 2 data of table2</td></tr>

                <tr><td>Row 2, column 1 data of table2</td>

                <td>Row 2, column 2 data of table2</td></tr>

            </tbody>

            <tfoot>

                <tr><td colspan="2">

                This is the footer of table 2</td></tr>

            </tfoot>

        </table>

        <button class="exportBtnClass">

                  Export to XLS file

         </button>

        <script>

            $(function() {

                $(".exportBtnClass").click(function(e){

                    var table = $(this).prev('.table2excel');

                    if(table && table.length){

                        var preserveColors = 

                       (table.hasClass('colorClass') ? true : false);

                        $(table).table2excel({

// This class's content is excluded from getting exported

                            exclude: ".noExl", 

                            name: "Output excel file ",

                            filename: 

"outputFile-" + new Date().toString().replace(/[-:.]/g, "") + ".xls",

                            fileext: ".xls", //File extension type

                            exclude_img: true,

                            exclude_links: true,

                            exclude_inputs: true,

                            preserveColors: preserveColors

                        });

                    }

                });        

            });

        </script>

    </body>

</html>

jQuery table2excel Plugin (https://github.com/rainabba/jquery-table2excel)

#Credit for the core table export code concept goes to insin (met on Freenode in #javascript) and core code inspired from https://gist.github.com/insin/1031969

FIRST!!

Thanks for your interest. I haven’t been able to maintain this and found the following project which looks well ahead of this one, so you may want to consider it first: TableExport

DISCLAIMER

This plugin is a hack on a hack. The .xls extension is the only way [some versions] of excel will even open it, and you will get a warning about the contents which can be ignored. The plugin was developed against Chrome and other have contributed code that should allow it to work in Firefox and Safari, but inconsistently since it’s a hack that’s not well supported anywhere but Chrome. I would not use this in public production personally and it was developed for an Intranet application where users are on Chrome and had known versions of Excel installed and the users were educated about the warning. These users also save-as in Excel so that when the files are distributed, the end-users don’t get the warning message.

Install — Bower

Install bower globally

Install jquery-table2excel and dependencies

bower install jquery-table2excel --save

Include jquery and table2excel in your page

<script src="bower_componentsjquerydistjquery.min.js"></script>
<script src="bower_componentsjquery-table2exceldistjquery.table2excel.min.js"></script>

Install — Legacy

Include jQuery and table2excel plugin:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>

Using the plugin

$("#yourHtmTable").table2excel({
    exclude: ".excludeThisClass",
    name: "Worksheet Name",
    filename: "SomeFile.xls", // do include extension
    preserveColors: false // set to true if you want background colors and font colors preserved
});

demo/

Contains a simple HTML file to demonstrate your plugin.

dist/

This is where the generated files are stored once Grunt runs.

.editorconfig

This file is for unifying the coding style for different editors and IDEs.

Check editorconfig.org if you haven’t heard about this project yet.

.jshintrc

List of rules used by JSHint to detect errors and potential problems in JavaScript.

Check jshint.com if you haven’t heard about this project yet.

.travis.yml

Definitions for continous integration using Travis.

Check travis-ci.org if you haven’t heard about this project yet.

table2excel.jquery.json

Package manifest file used to publish plugins in jQuery Plugin Registry.

Check this Package Manifest Guide for more details.

Gruntfile.js

Contains all automated tasks using Grunt.

Check gruntjs.com if you haven’t heard about this project yet.

package.json

Specify all dependencies loaded via Node.JS.

Check NPM for more details.

Contributing

Check CONTRIBUTING.md

History

Check Release list.

License

MIT License

JQuery Table2 Excel Example Tutorial

Hi Guys

In this tutorial, I will example you how to jquery table2 excel in convert. I am going to share an awesome plug-in for exporting the HTML table data to the excel sheet by a click of a button.

The table contains the <th> tags that define the headings for the table of HTML. The same headers act as the headings in the excel sheet after export. A few options may also be set like tab name in the excel sheet, the file name of excel etc in the jQuery code that I will explain after the demo.

Bellow The Script Used In The Demo:

<script>

$(function() {

$("button").click(function(){

$("#table2excel").table2excel({

exclude: ".noExl",

name: "Excel Document Name"

});

});

});

</script>

Here this example,the excel export file will download as the demo page loads.

Full Example

<!DOCTYPE html>

<html>

<head>

<title>JQuery Table2 Excel Example</title>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">

<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script src="https://www.jqueryscript.net/demo/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel/src/jquery.table2excel.js"></script>

</head>

<style type="text/css">

body{

background-color: #211c12;

}

.container{

margin-top:80px;

}

h1{

margin-bottom:20px;

}

table,table th{

text-align: center;

}

</style>

<body>

<div class="container">

<div class="row">

<div class="col-md-6 col-md-offset-3">

<h1 class="text-center">JQuery Table2 Excel Example</h1>

<table class="table table-bordered" id="table2excel">

<thead>

<tr style="background-color: #fff">

<th>#</th>

<th>Product Name</th>

<th>Product Price</th>

<th>Product Qut.</th>

</tr>

</thead>

<tbody>

<tr class="active">

<td>1</td>

<td>Product 1</td>

<td>200</td>

<td>2</td>

</tr>

<tr style="background-color: #fff">

<td>2</td>

<td>Product 2</td>

<td>220</td>

<td>5</td>

</tr>

<tr class="success">

<td>3</td>

<td>Product 3</td>

<td>300</td>

<td>4</td>

</tr>

<tr style="background-color: #fff">

<td>4</td>

<td>Product 4</td>

<td>500</td>

<td>2</td>

</tr>

<tr class="info">

<td>5</td>

<td>Product 5</td>

<td>550</td>

<td>8</td>

</tr>

</tbody>

</table>

<button class="btn btn-success">Export</button></div>

</div>

</div>

</div>

<script>

$(function() {

$("button").click(function(){

$("#table2excel").table2excel({

exclude: ".xls",

name: "Excel Document Name"

});

});

});

</script>

</body>

</html>

It will help you…

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

The reason the solution you found on the internet is no working is because of the line that starts var colCount. The variable mytable only has two elements being <thead> and <tbody>. The var colCount line is looking for all the elements within mytable that are <tr>. The best thing you can do is give an id to your <thead> and <tbody> and then grab all the values based on that. Say you had <thead id='headers'> :

function write_headers_to_excel() 
{
  str="";

  var myTableHead = document.getElementById('headers');
  var rowCount = myTableHead.rows.length;
  var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length; 

var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;

for(var i=0; i<rowCount; i++) 
{   
    for(var j=0; j<colCount; j++) 
    {           
        str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
        ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
    }
}

}

and then do the same thing for the <tbody> tag.

EDIT: I would also highly recommend using jQuery. It would shorten this up to:

function write_to_excel() 
{
 var ExcelApp = new ActiveXObject("Excel.Application");
 var ExcelSheet = new ActiveXObject("Excel.Sheet");
 ExcelSheet.Application.Visible = true; 

  $('th, td').each(function(i){
    ExcelSheet.ActiveSheet.Cells(i+1,i+1).Value = this.innerHTML;
  });
}

Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.

EDIT: To answer your question about how to do this for n number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:

var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++)
{
  write_headers_to_excel(tables[i]);
  write_bodies_to_excel(tables[i]);
}

Then change the function write_headers_to_excel() to function write_headers_to_excel(table). Then change var myTableHead = document.getElementById('headers'); to var myTableHead = table.getElementsByTagName('thead')[0];. Same with your write_bodies_to_excel() or however you want to set that up.

Introduction

This example shows how to export an HTML table to an Excel sheet using jquery table2excel plugin. 

What is table2excel?

table2excel is a jQuery Plugin. it is used to export HTML tables to Excel sheets. 

How to Include table2excel jQuery Plugin Within HTML File 

  1. <script type=«text/javascript» src=«https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js»></script>  
  2. <script src=«table2excel.js» type=«text/javascript»></script>    

table2excel.js Markup

Create one text document within the root directory of your project and save that document with name  table2excel.js 

After this, write the following code in table2excel.js file and save it.

  1.   
  2. ;  
  3. (function($, window, document, undefined) {  
  4.  var pluginName = «table2excel»
  5.   defaults = {  
  6.    exclude: «.noExl»,  
  7.    name: «Table2Excel»,  
  8.    filename: «table2excel»,  
  9.    fileext: «.xls»,  
  10.    exclude_img: true,  
  11.    exclude_links: true,  
  12.    exclude_inputs: true  
  13.   };  
  14.    
  15.  function Plugin(element, options) {  
  16.   this.element = element;  
  17.     
  18.     
  19.     
  20.     
  21.     
  22.   this.settings = $.extend({}, defaults, options);  
  23.   this._defaults = defaults;  
  24.   this._name = pluginName;  
  25.   this.init();  
  26.  }  
  27.  Plugin.prototype = {  
  28.   init: function() {  
  29.    var e = this;  
  30.    var utf8Heading = «<meta http-equiv=»content-type» content=»application/vnd.ms-excel; charset=UTF-8″>»;  
  31.    e.template = {  
  32.     head: «<html xmlns:o=»urn:schemas-microsoft-com:office:office» xmlns:x=»urn:schemas-microsoft-com:office:excel» xmlns=»http://www.w3.org/TR/REC-html40″>» + utf8Heading + «<head><!—[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>»,  
  33.     sheet: {  
  34.      head: «<x:ExcelWorksheet><x:Name>»,  
  35.      tail: «</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>»  
  36.     },  
  37.     mid: «</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]—></head><body>»,  
  38.     table: {  
  39.      head: «<table>»,  
  40.      tail: «</table>»  
  41.     },  
  42.     foot: «</body></html>»  
  43.    };  
  44.    e.tableRows = [];  
  45.      
  46.    $(e.element).each(function(i, o) {  
  47.     var tempRows = «»;  
  48.     $(o).find(«tr»).not(e.settings.exclude).each(function(i, p) {  
  49.      tempRows += «<tr>»;  
  50.      $(p).find(«td,th»).not(e.settings.exclude).each(function(i, q) {   
  51.       var rc = {  
  52.        rows: $(this).attr(«rowspan»),  
  53.        cols: $(this).attr(«colspan»),  
  54.        flag: $(q).find(e.settings.exclude)  
  55.       };  
  56.       if (rc.flag.length > 0) {  
  57.        tempRows += «<td> </td>»  
  58.       } else {  
  59.        if (rc.rows & rc.cols) {  
  60.         tempRows += «<td>» + $(q).html() + «</td>»;  
  61.        } else {  
  62.         tempRows += «<td»;  
  63.         if (rc.rows > 0) {  
  64.          tempRows += » rowspan='» + rc.rows + «‘ «;  
  65.         }  
  66.         if (rc.cols > 0) {  
  67.          tempRows += » colspan='» + rc.cols + «‘ «;  
  68.         }  
  69.         tempRows += «/>» + $(q).html() + «</td>»;  
  70.        }  
  71.       }  
  72.      });  
  73.      tempRows += «</tr>»;  
  74.      console.log(tempRows);  
  75.     });  
  76.       
  77.     if (e.settings.exclude_img) {  
  78.      tempRows = exclude_img(tempRows);  
  79.     }  
  80.       
  81.     if (e.settings.exclude_links) {  
  82.      tempRows = exclude_links(tempRows);  
  83.     }  
  84.       
  85.     if (e.settings.exclude_inputs) {  
  86.      tempRows = exclude_inputs(tempRows);  
  87.     }  
  88.     e.tableRows.push(tempRows);  
  89.    });  
  90.    e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);  
  91.   },  
  92.   tableToExcel: function(table, name, sheetName) {  
  93.    var e = this,  
  94.     fullTemplate = «»,  
  95.     i, link, a;  
  96.    e.format = function(s, c) {  
  97.     return s.replace(/{(w+)}/g, function(m, p) {  
  98.      return c[p];  
  99.     });  
  100.    };  
  101.    sheetName = typeof sheetName === «undefined» ? «Sheet» : sheetName;  
  102.    e.ctx = {  
  103.     worksheet: name || «Worksheet»,  
  104.     table: table,  
  105.     sheetName: sheetName  
  106.    };  
  107.    fullTemplate = e.template.head;  
  108.    if ($.isArray(table)) {  
  109.     for (i in table) {  
  110.        
  111.      fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;  
  112.     }  
  113.    }  
  114.    fullTemplate += e.template.mid;  
  115.   
  116.    if ($.isArray(table)) {  
  117.     for (i in table) {  
  118.      fullTemplate += e.template.table.head + «{table» + i + «}» + e.template.table.tail;  
  119.     }  
  120.    }  
  121.    fullTemplate += e.template.foot;  
  122.    for (i in table) {  
  123.     e.ctx[«table» + i] = table[i];  
  124.    }  
  125.    delete e.ctx.table;  
  126.    var isIE =  false || !!document.documentMode;   
  127.      
  128.    if (isIE) {  
  129.     if (typeof Blob !== «undefined») {  
  130.        
  131.      fullTemplate = e.format(fullTemplate, e.ctx);   
  132.      fullTemplate = [fullTemplate];  
  133.        
  134.      var blob1 = new Blob(fullTemplate, {  
  135.       type: «text/html»  
  136.      });  
  137.      window.navigator.msSaveBlob(blob1, getFileName(e.settings));  
  138.     } else {  
  139.        
  140.        
  141.      txtArea1.document.open(«text/html»«replace»);  
  142.      txtArea1.document.write(e.format(fullTemplate, e.ctx));  
  143.      txtArea1.document.close();  
  144.      txtArea1.focus();  
  145.      sa = txtArea1.document.execCommand(«SaveAs»true, getFileName(e.settings));  
  146.     }  
  147.    } else {  
  148.     var blob = new Blob([e.format(fullTemplate, e.ctx)], {  
  149.      type: «application/vnd.ms-excel»  
  150.     });  
  151.     window.URL = window.URL || window.webkitURL;  
  152.     link = window.URL.createObjectURL(blob);  
  153.     a = document.createElement(«a»);  
  154.     a.download = getFileName(e.settings);  
  155.     a.href = link;  
  156.     document.body.appendChild(a);  
  157.     a.click();  
  158.     document.body.removeChild(a);  
  159.    }  
  160.    return true;  
  161.   }  
  162.  };  
  163.  function getFileName(settings) {  
  164.   return (settings.filename ? settings.filename : «table2excel»);  
  165.  }  
  166.    
  167.  function exclude_img(string) {  
  168.   var _patt = /(s+alts*=s*«([^»]*)»|s+alts*=s*‘([^’]*)’)/i;  
  169.   return string.replace(/<img[^>]*>/gi, function myFunction(x) {  
  170.    var res = _patt.exec(x);  
  171.    if (res !== null && res.length >= 2) {  
  172.     return res[2];  
  173.    } else {  
  174.     return «»;  
  175.    }  
  176.   });  
  177.  }  
  178.    
  179.  function exclude_links(string) {  
  180.   return string.replace(/<a[^>]*>|</a>/gi, «»);  
  181.  }  
  182.    
  183.  function exclude_inputs(string) {  
  184.   var _patt = /(s+values*=s*«([^»]*)»|s+values*=s*‘([^’]*)’)/i;  
  185.   return string.replace(/<input[^>]*>|</input>/gi, function myFunction(x) {  
  186.    var res = _patt.exec(x);  
  187.    if (res !== null && res.length >= 2) {  
  188.     return res[2];  
  189.    } else {  
  190.     return «»;  
  191.    }  
  192.   });  
  193.  }  
  194.  $.fn[pluginName] = function(options) {  
  195.   var e = this;  
  196.   e.each(function() {  
  197.    if (!$.data(e, «plugin_» + pluginName)) {  
  198.     $.data(e, «plugin_» + pluginName, new Plugin(this, options));  
  199.    }  
  200.   });  
  201.     
  202.   return e;  
  203.  };  
  204. })(jQuery, window, document);  

HTML Markup

Now, create another text document within the root directory of your project and save it with the name of «Example.html».

After this, write the following code within your created Example.html file and save it. 

  1. <html  
  2.     xmlns=«http://www.w3.org/1999/xhtml»>  
  3.     <head>  
  4.         <title></title>  
  5.         <style type=«text/css»>    
  6.         body    
  7.         {    
  8.             font-family: Arial;    
  9.             font-size: 10pt;    
  10.         }    
  11.         table    
  12.         {    
  13.             border: 1px solid #ccc;    
  14.             border-collapse: collapse;    
  15.         }    
  16.         table th    
  17.         {    
  18.             background-color: #ff7f00;    
  19.             color: #fff;    
  20.             font-weight: bold;    
  21.         }    
  22.         table th, table td    
  23.         {    
  24.             padding: 5px;    
  25.             border: 1px solid #ccc;    
  26.         }    
  27.     </style>  
  28.     </head>  
  29.     <body>  
  30.         <table id=«tblEmployee» cellspacing=«0» cellpadding=«0»>  
  31.             <tr>  
  32.                 <th>Employee Id</th>  
  33.                 <th>Employee Name</th>  
  34.                 <th>Department</th>  
  35.             </tr>  
  36.             <tr>  
  37.                 <td>1</td>  
  38.                 <td>Nikunj Satasiya</td>  
  39.                 <td>Asp.Net</td>  
  40.             </tr>  
  41.             <tr>  
  42.                 <td>2</td>  
  43.                 <td>Hiren Dobariya</td>  
  44.                 <td>PHP</td>  
  45.             </tr>  
  46.             <tr>  
  47.                 <td>3</td>  
  48.                 <td>Vivek Ghadiya</td>  
  49.                 <td>Android</td>  
  50.             </tr>  
  51.             <tr>  
  52.                 <td>4</td>  
  53.                 <td>Pratik Pansuriya</td>  
  54.                 <td>SEO</td>  
  55.             </tr>  
  56.         </table>  
  57.         <br />  
  58.         <input type=«button» id=«btnExporttoExcel» value=«Export To Excel» />  
  59.         <script type=«text/javascript» src=«https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js»></script>  
  60.         <script src=«table2excel.js» type=«text/javascript»></script>  
  61.         <script type=«text/javascript»>    
  62.         $(function () {    
  63.             $(«#btnExporttoExcel»).click(function () {    
  64.                 $(«#tblEmployee»).table2excel({    
  65.                     filename: «Your_File_Name.xls»    
  66.                 });    
  67.             });    
  68.         });    
  69.     </script>  
  70.     </body>  
  71. </html>    

NOTE

At the end of table tag </table>, you need to add the following script.

  1. $(«#yourHtmTable»).table2excel({  
  2.  exclude: «.excludeThisClass»,  
  3.  name: «Worksheet Name»,  
  4.  filename: «SomeFile»  
  5. });   

Screenshots/Output

Output 

The screen after exporting HTML table to Excel sheet.

Output 

Summary

When the Export to Excel button is clicked, the jQuery table2excel plugin is applied to the created HTML table. The jQuery table2excel plugin accepts the file name as a parameter which sets the name of the Excel file.

Like this post? Please share to your friends:
  • Jquery datatables export excel
  • Jqgrid export to excel
  • Jpg перевести в word формат онлайн бесплатно
  • Jpg открыть в excel
  • Jpg открывается в word