将html表导出为CSV文件,始终返回空文件
我正在开发一个asp.net mvc5 Web应用程序。 我需要实现一个function,将Html表导出为.csv文件。 所以我添加了以下链接: –
Export Table data into Excel</a
>
我有以下脚本: –
$(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('"', '""'); // escape double quotes }).get().join(tmpColDelim); }).get().join(tmpRowDelim) .split(tmpRowDelim).join(rowDelim) .split(tmpColDelim).join(colDelim) + '"', // Data URI 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 exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']); // IF CSV, don't do event.preventDefault() or return false // We actually need this to be a typical hyperlink }); });
我在这个链接上使用tabletoCSV插件,如下: –
jQuery.fn.table2CSV = function (options) { var options = jQuery.extend({ separator: ',', header: [], delivery: 'popup' // popup, value }, options); var csvData = []; var headerArr = []; var el = this; //header var numCols = options.header.length; var tmpRow = []; // construct header avalible array if (numCols > 0) { for (var i = 0; i 0 && tmp != '') { var mystr = tmpRow.join(options.separator); csvData[csvData.length] = mystr; } } function formatData(input) { // replace " with “ var regexp = new RegExp(/["]/g); var output = input.replace(regexp, "“"); //HTML var regexp = new RegExp(/\<[^\/g); var output = output.replace(regexp, ""); if (output == "") return ''; return '"' + output + '"'; } function popup(data) { var generator = window.open('', 'csv', 'height=400,width=600'); generator.document.write('CSV '); generator.document.write(''); generator.document.write(''); generator.document.write(''); generator.document.close(); return true; } };
目前我有以下标记,显示一个表和导出超链接: –
Name User Groups Security Roles Edit | Delete de The are 0 Users. Edit only me The are 10 Users. Edit | Delete rwerwe The are 0 Users. Edit users The are 1 Users. Edit w The are 5 Users.