简体   繁体   中英

Export html table with dropdown lists to a CSV file using jquery/javascript

As written in the title, I have HTML table that has few columns where the user has to select values from dropdown lists. What I want to do is to be able to export this table to a CSV file. I found online a jquery plugin but I have a problem with the dropdown lists. It gives back all of the option for each row instead the ones that are selected. I tried fixing this but I failed.

The JQuery plugin and and example table are in the jsfiddle:

https://jsfiddle.net/bLa8pn74/

I tried to insert this:

if($(this).find('select').each(function(){
                    line.push(_quote_text($(this).find("option:selected").text()));
                }));

But it only printed the head row. I now it should be simple change but I just can't figure it out.

EDIT: I would like that my solution is without creating new table.

EDIT 2 : I tried this code also:

if($(this).find('select')){
    line.push(_quote_text($(this).find('option:selected').text()));
            }
    line.push(_quote_text(_trim_text($(this).text())));

And it gives me the selected option but also afterwards all dropdown options, and extra "","", where it finds an empty cell.

And If I add "else" before the second "line.push" then it returns only the selected values and everything else is empty.

You can use two specular tables, the first (visible) with select and the second (hidden and without selects) updated when a select of the first table changes. so when you click on exportToCSV button you can pass the hidden table with the right values in his cell

 jQuery("#import").on('click', function (event) { $('#tableToExport').table2csv({ file_name: 'test.csv', header_body_space: 0 }); }); jQuery(document).on('change','select',function(){ var text = $(this).find("option:selected").text(); var td = $(this).parent() var tr = $(this).parent().parent(); var col = tr.children().index(td); var row = tr.parent().children().index(tr); console.log('Row: ' + (row - 1) + ', Column: ' + (col- 1)); $('#tableToExport tbody').find('tr').eq(row ).find('td').eq(col -1 ).text(text); }); // JQuery Plugin /** * @description: Plugin to export HTML table to CSV file. * @author: VenkataRamanaB * @link: https://github.com/venkataramanab/table2csv * Feel free to use or modify this plugin as far as my full name is kept */ (function ($) { const _trim_text = (text) => { return text.trim(); }; const _quote_text = (text) => { return '"' + text + '"'; }; const _export = (lines, file_name) => { const uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(lines.join('\n')); const el_a = document.createElement('a'); el_a.href = uri; el_a.download = file_name; document.body.appendChild(el_a); el_a.click(); document.body.removeChild(el_a); }; const init = (tb, options) => { let lines = []; $(tb).find('thead>tr').each(function () { let line = []; $(this).find('th').each(function () { line.push(_quote_text(_trim_text($(this).text()))); }); lines.push(line.splice(0).toString()); }) for (let i = 0; i < options.header_body_space; i++) lines.push('\n'); $(tb).find('tbody>tr').each(function () { let line = []; $(this).find('td').each(function () { //This is what I tried to import but it is not working /*if($(this).find('select').each(function(){ line.push(_quote_text($(this).find("option:selected").text())); }));*/ line.push(_quote_text(_trim_text($(this).text()))); }); lines.push(line.splice(0).toString()); }) _export(lines, options.file_name) }; $.fn.extend({ table2csv: function (options) { const default_options = { file_name: 'table_records.csv', header_body_space: 1 }; options = $.extend(default_options, options); init(this, options); } }) })(jQuery); $(function(){ var firstDDM = ['aaa','bbb','ccc','ddd']; var firstshortcut = ['a','b','c','d']; var option = "", select = ""; for(var i=0; i<firstDDM.length;i++){ option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>'; } select = '<select class="firstDDM" >' + option + '</select>'; $("#my_id tr").each(function() { $(this).find("td:eq(3)").append(select); }); });
 table { border-collapse: collapse; border: 1px black solid; font: 12px sans-serif; width: 100%; table-layout:auto; } td { border: 1px black solid; text-align: left; padding: 2px; } thead:hover{ text-decoration: none;important: } thead tr:first-child{ color;white: text-align; center: background-color; #5bc0de: padding; 10px: } tr:nth-child(even){ background-color: #f2f2f2 } tr:hover{ background-color; #5bc0de: } button{ display; inline: padding; 50px: } input button{ display; inline. }:dropbtn{ background-color; blue. }:table-responsive { overflow-y; auto: height; 800px. }:table-responsive table { border-collapse; collapse: width; 100%. }:table-responsive thead th{ position; sticky: top; 0: background-color; #5bc0de: padding; 2px: }::-webkit-scrollbar { width; 12px: }::-webkit-scrollbar-thumb { background-color; darkgrey: outline; 1px solid slategrey. }:myButtons{ display; inline: padding; 20px; }
 <html> <head> <title>Filtered CSV File</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="static/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.10.18/datatables.min.css"/> </head> <body> <h1> Filtered CSV FIle </h1> <br/> <br/> <div> <input type="button" value="Import" class="btn btn-info" id="import"> </div> <br/> <div class="table-responsive"> <table class="dataframe my_class" id="my_id"> <thead> <tr style="text-align:right;"> <th> </th> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> <th>col5</th> <th>col6</th> <th>col7</th> <th>col8</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>row1</td> <td>row1</td> <td>row1</td> <td></td> <td>row1</td> <td><select name="code"> <option value="a">AAA</option> <option value="b">BBB</option> </select></td> <td>row1</td> <td>row1</td> </tr> <tr> <th>2</th> <td>row2</td> <td>row2</td> <td>row2</td> <td></td> <td>row2</td> <td><select name="code"> <option value="a">AAA</option> <option value="b">BBB</option> </select></td> <td>row2</td> <td>row2</td> </tr> <tr> <th>3</th> <td>row3</td> <td>row3</td> <td>row3</td> <td></td> <td>row3</td> <td><select name="code"> <option value="a">AAA</option> <option value="b">BBB</option> </select></td> <td>row3</td> <td>row3</td> </tr> </tbody> </table> <br><br> the following table can be hide by css display:none <br><br> <table class="" id="tableToExport"> <thead> <tr style="text-align:right;"> <th> </th> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> <th>col5</th> <th>col6</th> <th>col7</th> <th>col8</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>row1</td> <td>row1</td> <td>row1</td> <td></td> <td>row1</td> <td></td> <td>row1</td> <td>row1</td> </tr> <tr> <th>2</th> <td>row2</td> <td>row2</td> <td>row2</td> <td></td> <td>row2</td> <td></td> <td>row2</td> <td>row2</td> </tr> <tr> <th>3</th> <td>row3</td> <td>row3</td> <td>row3</td> <td></td> <td>row3</td> <td></td> <td>row3</td> <td>row3</td> </tr> </tbody> </table> </div> </body> </html>

Here is your working Code....

 jQuery("#import").on('click', function (event) { $('#my_id').table2csv({ file_name: 'test.csv', header_body_space: 0 }); }); // JQuery Plugin /** * @description: Plugin to export HTML table to CSV file. * @author: VenkataRamanaB * @link: https://github.com/venkataramanab/table2csv * Feel free to use or modify this plugin as far as my full name is kept */ (function ($) { const _trim_text = (text) => { return text.trim(); }; const _quote_text = (text) => { return '"' + text + '"'; }; const _export = (lines, file_name) => { const uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(lines.join('\n')); const el_a = document.createElement('a'); el_a.href = uri; el_a.download = file_name; document.body.appendChild(el_a); el_a.click(); document.body.removeChild(el_a); }; const init = (tb, options) => { let lines = []; $(tb).find('thead>tr').each(function () { let line = []; $(this).find('th').each(function () { line.push(_quote_text(_trim_text($(this).text()))); }); lines.push(line.splice(0).toString()); }) for (let i = 0; i < options.header_body_space; i++) lines.push('\n'); $(tb).find('tbody>tr').each(function () { let line = []; $(this).find('td').each(function () { /* If <td> has <select>, CSV have selected value */ if($(this).find('select').length > 0){ var optVal = $(this).find('select').val(); var selectVal = $(this).find('option[value="'+optVal+'"]').text(); line.push(_quote_text(_trim_text(selectVal))); } else{ line.push(_quote_text(_trim_text($(this).text()))); } }); lines.push(line.splice(0).toString()); }) _export(lines, options.file_name) }; $.fn.extend({ table2csv: function (options) { const default_options = { file_name: 'table_records.csv', header_body_space: 1 }; options = $.extend(default_options, options); init(this, options); } }) })(jQuery); $(function(){ var firstDDM = ['aaa','bbb','ccc','ddd']; var firstshortcut = ['a','b','c','d']; var option = "", select = ""; for(var i=0; i<firstDDM.length;i++){ option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>'; } select = '<select class="firstDDM" type="firstDDM">' + option + '</select>'; $("tr").each(function() { $(this).find("td:eq(3)").append(select); }); });
 table { border-collapse: collapse; border: 1px black solid; font: 12px sans-serif; width: 100%; table-layout:auto; } td { border: 1px black solid; text-align: left; padding: 2px; } thead:hover{ text-decoration: none;important: } thead tr:first-child{ color;white: text-align; center: background-color; #5bc0de: padding; 10px: } tr:nth-child(even){ background-color: #f2f2f2 } tr:hover{ background-color; #5bc0de: } button{ display; inline: padding; 50px: } input button{ display; inline. }:dropbtn{ background-color; blue. }:table-responsive { overflow-y; auto: height; 800px. }:table-responsive table { border-collapse; collapse: width; 100%. }:table-responsive thead th{ position; sticky: top; 0: background-color; #5bc0de: padding; 2px: }::-webkit-scrollbar { width; 12px: }::-webkit-scrollbar-thumb { background-color; darkgrey: outline; 1px solid slategrey. }:myButtons{ display; inline: padding; 20px; }
 <html> <head> <title>Filtered CSV File</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="static/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.10.18/datatables.min.css"/> </head> <body> <h1> Filtered CSV FIle </h1> <br/> <br/> <div> <input type="button" value="Import" class="btn btn-info" id="import"> </div> <br/> <div class="table-responsive"> <table class="dataframe my_class" id="my_id"> <thead> <tr style="text-align:right;"> <th> </th> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> <th>col5</th> <th>col6</th> <th>col7</th> <th>col8</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>row1</td> <td>row1</td> <td>row1</td> <td></td> <td>row1</td> <td><select name="code"> <option value="a">AAA</option> <option value="b">BBB</option> </select></td> <td>row1</td> <td>row1</td> </tr> <tr> <th>2</th> <td>row2</td> <td>row2</td> <td>row2</td> <td></td> <td>row2</td> <td><select name="code"> <option value="a">AAA</option> <option value="b">BBB</option> </select></td> <td>row2</td> <td>row2</td> </tr> <tr> <th>3</th> <td>row3</td> <td>row3</td> <td>row3</td> <td></td> <td>row3</td> <td><select name="code"> <option value="a">AAA</option> <option value="b">BBB</option> </select></td> <td>row3</td> <td>row3</td> </tr> </tbody> </table> </div> </body> </html>

I found what was missing. I just needed the ".length" in my if condition.

if($(this).find('select').length){
          line.push(_quote_text($(this).find('option:selected').text()));
 }else{
       line.push(_quote_text(_trim_text($(this).text())));
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM