如何将 html 表格数据导出为 .csv 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7161113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I export html table data as .csv file?
提问by forrest
I have a table of data in an html table on a website and need to know how to export that data as .csv file.
我在网站上的 html 表中有一个数据表,需要知道如何将该数据导出为 .csv 文件。
How would this be done?
这将如何完成?
回答by AlphaMale
For exporting html to csv try following this example. More details and examples are available at the author's website.
要将 html 导出到 csv,请尝试遵循此示例。更多细节和示例可在作者的网站上找到。
Create a html2csv.js file and put the following code in it.
创建一个 html2csv.js 文件并将以下代码放入其中。
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 < numCols; i++) {
tmpRow[tmpRow.length] = formatData(options.header[i]);
}
} else {
$(el).filter(':visible').find('th').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
}
row2CSV(tmpRow);
// actual data
$(el).find('tr').each(function() {
var tmpRow = [];
$(this).filter(':visible').find('td').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
row2CSV(tmpRow);
});
if (options.delivery == 'popup') {
var mydata = csvData.join('\n');
return popup(mydata);
} else {
var mydata = csvData.join('\n');
return mydata;
}
function row2CSV(tmpRow) {
var tmp = tmpRow.join('') // to remove any blank rows
// alert(tmp);
if (tmpRow.length > 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('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
};
include the js files into the html page like this:
将 js 文件包含到 html 页面中,如下所示:
<script type="text/javascript" src="jquery-1.3.2.js" ></script>
<script type="text/javascript" src="html2CSV.js" ></script>
TABLE:
桌子:
<table id="example1" border="1" style="background-color:#FFFFCC" width="0%" cellpadding="3" cellspacing="3">
<tr>
<th>Title</th>
<th>Name</th>
<th>Phone</th>
</tr>
<tr>
<td>Mr.</td>
<td>John</td>
<td>07868785831</td>
</tr>
<tr>
<td>Miss</td>
<td><i>Linda</i></td>
<td>0141-2244-5566</td>
</tr>
<tr>
<td>Master</td>
<td>Hyman</td>
<td>0142-1212-1234</td>
</tr>
<tr>
<td>Mr.</td>
<td>Bush</td>
<td>911-911-911</td>
</tr>
</table>
EXPORT BUTTON:
导出按钮:
<input value="Export as CSV 2" type="button" onclick="$('#example1').table2CSV({header:['prefix','Employee Name','Contact']})">
回答by Michael Singer
I was able to use the answer outlined here: Export to CSV using jQuery and htmland added in a modification to make it work in IE and another modification mentioned in the comments to grab the thead from the table.
我能够使用这里概述的答案:使用 jQuery 和 html 导出到 CSV并添加了一个修改以使其在 IE 中工作,以及评论中提到的另一个修改以从表格中获取 thead。
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td),tr:has(th)'),
// 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,th');
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) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
console.log(csv);
if (window.navigator.msSaveBlob) { // IE 10+
//alert('IE' + csv);
window.navigator.msSaveOrOpenBlob(new Blob([csv], {type: "text/plain;charset=utf-8;"}), "csvname.csv")
}
else {
$(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' });
}
}
// This must be a hyperlink
$("#xx").on('click', function (event) {
exportTableToCSV.apply(this, [$('#projectSpreadsheet'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
With my link looking like this...
我的链接看起来像这样......
<a href="#" id="xx" style="text-decoration:none;color:#000;background-color:#ddd;border:1px solid #ccc;padding:8px;">Export Table data into Excel</a>
JsFiddle: https://jsfiddle.net/mnsinger/65hqxygo/
JsFiddle:https://jsfiddle.net/mnsinger/65hqxygo/
回答by gene tsai
Here is a really quick CoffeeScript/jQuery example
这是一个非常快速的 CoffeeScript/jQuery 示例
csv = []
for row in $('#sometable tr')
csv.push ("\"#{col.innerText}\"" for col in $(row).find('td,th')).join(',')
output = csv.join("\n")
回答by Roozbeh Zabihollahi
Thanks to gene tsai
, here is some modifications to his code to run on my target page:
感谢gene tsai
,这里对他的代码进行了一些修改,以便在我的目标页面上运行:
csv = []
rows = $('#data tr');
for(i =0;i < rows.length;i++) {
cells = $(rows[i]).find('td,th');
csv_row = [];
for (j=0;j<cells.length;j++) {
txt = cells[j].innerText;
csv_row.push(txt.replace(",", "-"));
}
csv.push(csv_row.join(","));
}
output = csv.join("\n")
improvements:
改进:
- Use generic JavaScript
for
loop - make sure each cell does not have a comma
- 使用通用 JavaScript
for
循环 - 确保每个单元格没有逗号
回答by dabeng
The following solution can do it.
以下解决方案可以做到。
$(function() {
$("button").on('click', function() {
var data = "";
var tableData = [];
var rows = $("table tr");
rows.each(function(index, row) {
var rowData = [];
$(row).find("th, td").each(function(index, column) {
rowData.push(column.innerText);
});
tableData.push(rowData.join(","));
});
data += tableData.join("\n");
$(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {
type: "text/csv"
})) + '/>');
$('#download-link')[0].click();
$('#download-link').remove();
});
});
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid #aaa;
padding: 0.5rem;
text-align: left;
}
td {
font-size: 0.875rem;
}
.btn-group {
padding: 1rem 0;
}
button {
background-color: #fff;
border: 1px solid #000;
margin-top: 0.5rem;
border-radius: 3px;
padding: 0.5rem 1rem;
font-size: 1rem;
}
button:hover {
cursor: pointer;
background-color: #000;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Author</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>jQuery</td>
<td>John Resig</td>
<td>The Write Less, Do More, JavaScript Library.</td>
</tr>
<tr>
<td>React</td>
<td>Jordan Walke</td>
<td>React makes it painless to create interactive UIs.</td>
</tr>
<tr>
<td>Vue.js</td>
<td>Yuxi You</td>
<td>The Progressive JavaScript Framework.</td>
</tr>
</tbody>
</table>
<div class="btn-group">
<button>csv</button>
</div>
回答by Jasty
You could use an extension for Chrome, that works well the times I have tried it.
您可以使用 Chrome 的扩展程序,这在我尝试过的时候效果很好。
https://chrome.google.com/webstore/search/html%20table%20to%20csv?_category=extensions
https://chrome.google.com/webstore/search/html%20table%20to%20csv?_category=extensions
When installed and on any web page with a table if you click on this extension's icon it shows all the tables in the page, highlighting each as you roll over the tables it lists, clicking allows you to copy it to the clipboard or save it to a Google Doc.
安装后并在任何带有表格的网页上,如果您单击此扩展程序的图标,它会显示页面中的所有表格,在您滚动列出的表格时突出显示每个表格,单击允许您将其复制到剪贴板或将其保存到一个谷歌文档。
It works perfectly for what I need, which is occasional conversion of web based tabular data into a spreadsheet I can work with.
它非常适合我的需要,偶尔将基于 Web 的表格数据转换为我可以使用的电子表格。
回答by n8henrie
I've briefly covered a simple way to do this with Google Spreadsheets (importHTML
) and in Python (Pandas read_html
and to_csv
) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.
我在此处的 SO 回答中简要介绍了使用 Google 电子表格 ( importHTML
) 和 Python (Pandasread_html
和to_csv
) 以及示例 Python 脚本执行此操作的简单方法:https: //stackoverflow.com/a/28083469/1588795。
回答by dat
If it's an infrequent need, try one of several firefox addons which facilitate copying HTML table data to the clipboard (e.g., https://addons.mozilla.org/en-US/firefox/addon/dafizilla-table2clipboard/). For example, for the 'table2clipboard' add-on:
如果不经常需要,请尝试几个有助于将 HTML 表格数据复制到剪贴板的 firefox 插件之一(例如,https: //addons.mozilla.org/en-US/firefox/addon/dafizilla-table2clipboard/)。例如,对于“table2clipboard”附加组件:
- install the add-on in firefox
- open the web-page (with the table) in firefox
- right-click anywhere in the table and select 'copy whole table'
- start up a spreadsheet application such as LibreOffice Calc
- paste into the spreadsheet (select appropriate separator character as needed)
- save/export the spreadsheet as CSV.
- 在 Firefox 中安装附加组件
- 在 Firefox 中打开网页(带有表格)
- 右键单击表格中的任意位置并选择“复制整个表格”
- 启动电子表格应用程序,例如 LibreOffice Calc
- 粘贴到电子表格中(根据需要选择适当的分隔符)
- 将电子表格保存/导出为 CSV。