[英]Export table to CSV - string formatting issue into separate cells
I have several HTML tables that I want to allow the user to export its content to a csv. 我有几个HTML表,希望允许用户将其内容导出到csv。
I currently have this solution implemented and it almost works perfectly: 我目前已经实现了该解决方案,并且几乎可以完美地运行:
function exportTableToCsv($table, filename) {
var $rows = $table.find('tr:has(td,th)'),
tmpColDelim = String.fromCharCode(11),
tmpRowDelim = String.fromCharCode(0),
colDelim = ' ',
rowDelim = '"\r\n"',
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('"', '""');
}).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'
});
}
Which I call like this: 我这样称呼:
$(".ExportSummary").on('click', function () {
exportTableToCsv.apply(this, [$('#SummaryTable'), 'ExportSummary.csv']);
});
Now, my issue is that I cannot get the string formatting to work by putting the <td>
in separate cells in Excel. 现在, 我的问题是 ,无法通过将<td>
放在Excel中的单独单元格中来使字符串格式正常工作。 I simply don't know how to get the text to be placed in separated cells since it is being mapped together into a whole string content. 我只是不知道如何将文本放置在单独的单元格中,因为它被一起映射到整个字符串内容中。
I want the desired output that is provided with this JsFiddle - but this solution does not provide the ability to choose filename and setting the appropiate content-type (application/csv) to be recognized by the browser. 我希望此JsFiddle提供所需的输出-但是此解决方案不提供选择文件名和设置适当的内容类型(应用程序/ csv)以被浏览器识别的功能。
Any help is appreciated. 任何帮助表示赞赏。 Thanks in advance! 提前致谢!
http://en.wikipedia.org/wiki/Comma-separated_values#Example http://en.wikipedia.org/wiki/Comma-separated_values#Example
USA/UK CSV file the decimal separator is a period/full stop and the value separator is a comma. USA / UK CSV文件,十进制分隔符是句点/句号,而值分隔符是逗号。 European CSV/DSV file the decimal separator is a comma and the value separator is a semicolon 欧洲CSV / DSV文件,十进制分隔符是逗号,值分隔符是分号
I have modified a little bit your script: 我对您的脚本进行了一些修改:
function exportTableToCsv($table, filename) {
...
// 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();
...
http://jsfiddle.net/mu5g1a7x/2/ http://jsfiddle.net/mu5g1a7x/2/
Let me know, if I understood you correctly. 如果我理解正确,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.