使用jQuery和html导出为CSV
我有一个表格数据,我需要导出到CSV没有使用任何外部插件或API。 我使用了传递MIMEtypes的window.open
方法,但遇到了如下的问题:
如何确定Microsoft Excel或Open Office是否安装在使用jQuery的系统上
代码应该独立于系统上正在安装什么,即openoffice或ms excel。 我相信CSV是这两种编辑能够期待的格式。
码
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/JavaScript"> $(document).ready(function(){ $("#btnExport").click(function(e) { var msg = GetMimeTypes(); //OpenOffice window.open('data:application/vnd.oasis.opendocument.spreadsheet,' + $('#dvData').html()); //MS-Excel window.open('data:application/vnd.ms-excel,' + $('#dvData').html()); //CSV window.open('data:application/csv,charset=utf-8,' + $('#dvData').html()); e.preventDefault(); }); }); function GetMimeTypes () { var message = ""; // Internet Explorer supports the mimeTypes collection, but it is always empty if (navigator.mimeTypes && navigator.mimeTypes.length > 0) { var mimes = navigator.mimeTypes; for (var i=0; i < mimes.length; i++) { message += "<b>" + mimes[i].type + "</b> : " + mimes[i].description + "<br />"; } } else { message = "Your browser does not support this "; //sorry! } return ( message); } </script> </head> <body> <div id="dvData"> <table> <tr> <th>Column One </th> <th>Column Two</th> <th>Column Three</th> </tr> <tr> <td>row1 Col1</td> <td>row1 Col2</td> <td>row1 Col3</td> </tr> <tr> <td>row2 Col1</td> <td>row2 Col2</td> <td>row2 Col3</td> </tr> <tr> <td>row3 Col1</td> <td>row3 Col2</td> <td>row3 Col3</td> </tr> </table> </div> <br/> <input type="button" id="btnExport" value=" Export Table data into Excel " /> </body>
错误:
CSV:通过浏览器无法识别
ODS和Excel:正在工作,但我无法find系统安装了Excel或安装了openoffice时要生成哪一个?
IE版本8:它完全不工作,打开一个新的窗口,如下截图。
先来演示一下,然后再解释一下:
$(document).ready(function() { function exportTableToCSV($table, filename) { var $rows = $table.find('tr:has(td)'), // Temporary delimiter characters unlikely to be typed by keyboard // This is to avoid accidentally splitting the actual contents 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), $cols = $row.find('td'); return $cols.map(function(j, col) { var $col = $(col), text = $col.text(); 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' // This is here just for completeness // Remove the 'false' at your own risk 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 }); });
a.export, a.export:visited { display: inline-block; text-decoration: none; color: #000; background-color: #ddd; border: 1px solid #ccc; padding: 8px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" class="export">Export Table data into Excel</a> <div id="dvData"> <table> <tr> <th>Column One</th> <th>Column Two</th> <th>Column Three</th> </tr> <tr> <td>row1 Col1</td> <td>row1 Col2</td> <td>row1 Col3</td> </tr> <tr> <td>row2 Col1</td> <td>row2 Col2</td> <td>row2 Col3</td> </tr> <tr> <td>row3 Col1</td> <td>row3 Col2</td> <td>row3 Col3</td> </tr> <tr> <td>row4 'Col1'</td> <td>row4 'Col2'</td> <td>row4 'Col3'</td> </tr> <tr> <td>row5 "Col1"</td> <td>row5 "Col2"</td> <td>row5 "Col3"</td> </tr> <tr> <td>row6 "Col1"</td> <td>row6 "Col2"</td> <td>row6 "Col3"</td> </tr> </table> </div>
我不确定上面的CSV生成代码是否好像跳过了单元格,也没有显示逗号。 所以这里是我的CSV代码,可能是有用的。
它确实假设你有$table
variables这是一个jQuery对象(例如var $table = $('#yourtable');
)
$rows = $table.find('tr'); var csvData = ""; for(var i=0;i<$rows.length;i++){ var $cells = $($rows[i]).children('th,td'); //header or content cells for(var y=0;y<$cells.length;y++){ if(y>0){ csvData += ","; } var txt = ($($cells[y]).text()).toString().trim(); if(txt.indexOf(',')>=0 || txt.indexOf('\"')>=0 || txt.indexOf('\n')>=0){ txt = "\"" + txt.replace(/\"/g, "\"\"") + "\""; } csvData += txt; } csvData += '\n'; }
@Terry Young的微小更新回答,即添加IE 10+支持
if (window.navigator.msSaveOrOpenBlob) { // IE 10+ var blob = new Blob([decodeURIComponent(encodeURI(csvString))], { type: 'text/csv;charset=' + document.characterSet }); window.navigator.msSaveBlob(blob, filename); } else { // actual real browsers //Data URI csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvData); $(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); }
如果您将数据转换为CSV格式并将其转换为HTML以便在网页上显示,该怎么办? 您可以使用http://code.google.com/p/js-tables/插件。; 检查这个例子http://code.google.com/p/js-tables/wiki/Table因为你已经在使用jQuery库,我假定你可以添加其他JavaScript工具箱库。;
如果数据是CSV格式,你应该能够使用通用的'application / octetstream'MIMEtypes。 您尝试过的所有3个MIMEtypes都取决于安装在客户端计算机上的软件。
据我所知,你有你的数据在一张桌子上,你想从这些数据创buildCSV。 但是,您在创buildCSV时遇到问题。
我的想法是迭代和parsing表的内容,并从parsing的数据中生成一个string。 例如,您可以检查如何将JSON转换为CSV格式并存储在variables中。 你在你的例子中使用jQuery,所以不会算作外部插件。 然后,你只需要使用window.open
提供结果string,并按照build议使用application/octetstream
。
<a id="export" role='button'> Click Here To Download Below Report </a> <table id="testbed_results" style="table-layout:fixed"> <thead> <tr width="100%" style="color:white" bgcolor="#3195A9" id="tblHeader"> <th>Name</th> <th>Date</th> <th>Speed</th> <th>Column2</th> <th>Interface</th> <th>Interface2</th> <th>Sub</th> <th>COmpany result</th> <th>company2</th> <th>Gen</th> </tr> </thead> <tbody> <tr id="samplerow"> <td>hello</td> <td>100</td> <td>200</td> <td>300</td> <td>html2svc</td> <td>ajax</td> <td>200</td> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>hello</td> <td>100</td> <td>200</td> <td>300</td> <td>html2svc</td> <td>ajax</td> <td>200</td> <td>7</td> <td>8</td> <td>9</td> </tr> </tbody> </table>
$(document).ready(function () { Html2CSV('testbed_results', 'myfilename','export'); }); function Html2CSV(tableId, filename,alinkButtonId) { var array = []; var headers = []; var arrayItem = []; var csvData = new Array(); $('#' + tableId + ' th').each(function (index, item) { headers[index] = '"' + $(item).html() + '"'; }); csvData.push(headers); $('#' + tableId + ' tr').has('td').each(function () { $('td', $(this)).each(function (index, item) { arrayItem[index] = '"' + $(item).html() + '"'; }); array.push(arrayItem); csvData.push(arrayItem); }); var fileName = filename + '.csv'; var buffer = csvData.join("\n"); var blob = new Blob([buffer], { "type": "text/csv;charset=utf8;" }); var link = document.getElementById(alinkButton); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute link.setAttribute("href", window.URL.createObjectURL(blob)); link.setAttribute("download", fileName); } else if (navigator.msSaveBlob) { // IE 10+ link.setAttribute("href", "#"); link.addEventListener("click", function (event) { navigator.msSaveBlob(blob, fileName); }, false); } else { // it needs to implement server side export link.setAttribute("href", "http://www.example.com/export"); } } </script>