使用jQuery导出CSV表格时表头未下载的问题求助
Fix: Include Table Headers When Exporting to CSV with jQuery
Got it, let's fix that missing header issue! The root cause is your current code only targets table rows that contain <td> elements (the body rows) and completely ignores the <th> header row in the <thead> section. Here's the adjusted code that will include the headers in your exported CSV:
Modified JavaScript Code
$(document).ready(function() { function exportTableToCSV($table, filename) { // Include both header rows (thead tr) and body rows (tbody tr) var $rows = $table.find('thead tr, tbody tr'), // Temporary delimiter characters unlikely to be typed by keyboard tmpColDelim = String.fromCharCode(11), // vertical tab character tmpRowDelim = String.fromCharCode(0), // null character // actual delimiter characters for CSV format colDelim = '"","', rowDelim = '"\r\n"', // Grab text from table into CSV formatted string csv = '"' + $rows.map(function(i, row) { var $row = $(row), // Capture text from both th (headers) and td (body cells) $cols = $row.find('th, td'); return $cols.map(function(j, col) { var $col = $(col), text = $col.text().trim(); // Optional: trim extra whitespace return text.replace(/"/g, '""'); // escape double quotes }).get().join(tmpColDelim); }).get().join(tmpRowDelim) .split(tmpRowDelim).join(rowDelim) .split(tmpColDelim).join(colDelim) + '"'; // Deliberate 'false', see comment below if (false && window.navigator.msSaveBlob) { var blob = new Blob([decodeURIComponent(csv)], { type: 'text/csv;charset=utf8' }); // Crashes in IE 10, IE 11 and Microsoft Edge // See MS Edge Issue #10396033 // Hence, the deliberate 'false' window.navigator.msSaveBlob(blob, filename); } else if (window.Blob && window.URL) { // HTML5 Blob var blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }); var csvUrl = URL.createObjectURL(blob); $(this) .attr({ 'download': filename, 'href': csvUrl }); } else { // Data URI var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv); $(this) .attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); } } // This must be a hyperlink $(".export").on('click', function(event) { // CSV var args = [$('#dvData>table'), 'export.csv']; exportTableToCSV.apply(this, args); // If CSV, don't do event.preventDefault() or return false // We actually need this to be a typical hyperlink }); });
Your Existing HTML (No Changes Needed)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> <div class="box"> <div class="box-header"> <a href="#" class="export">Export Table data into Excel</a> </div> <!-- /.box-header --> <div class="box-body dvData" id="dvData"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>Rendering engine</th> <th>Browser</th> <th>Platform(s)</th> <th>Engine version</th> <th>CSS grade</th> </tr> </thead> <tbody> <tr> <td>Trident</td> <td>Internet Explorer 4.0 </td> <td>Win 95+</td> <td> 4</td> <td>X</td> </tr> <tr> <td>Trident</td> <td>Internet Explorer 5.0 </td> <td>Win 95+</td> <td>5</td> <td>C</td> </tr> <tr> <td>Trident</td> <td>Internet Explorer 5.5 </td> <td>Win 95+</td> <td>5.5</td> <td>A</td> </tr> <tr> <td>Trident</td> <td>Internet Explorer 6 </td> <td>Win 98+</td> <td>6</td> <td>A</td> </tr> <tr> <td>Trident</td> <td>Internet Explorer 7</td> <td>Win XP SP2+</td> <td>7</td> <td>A</td> </tr> </tfoot> </table> </div> <!-- /.box-body --> </div> <!-- /.box -->
Key Changes Explained
- Row Selection: Changed
$table.find('tr:has(td)')to$table.find('thead tr, tbody tr')to ensure we include both the header row and all body rows. - Column Selection: Updated
$row.find('td')to$row.find('th, td')so we extract text from both header cells (<th>) and body cells (<td>). - Optional Trim: Added
.trim()totext = $col.text().trim()to clean up any extra whitespace in your table cells (you can remove this if you want to preserve original spacing).
Now when you click the "Export Table data into Excel" link, your downloaded CSV will include the full header row followed by all your table content!
内容的提问来源于stack exchange,提问作者Mithun M
相关产品推荐
相关产品推荐

