问题
I am using the below jsfiddle code to separate the code to create csv file.It works fine except when there is comma in my column text.How can I change the separator?
http://jsfiddle.net/5KRf6/3/
function makeCSV() {
var csv = "";
$("table").find("tr").each(function () {
var sep = "";
$(this).find("input").each(function () {
csv += sep + $(this).val();
sep = ",";
});
csv += "\n";
});
$("#csv").text(csv);
window.URL = window.URL || window.webkiURL;
var blob = new Blob([csv]);
var blobURL = window.URL.createObjectURL(blob);
$("#downloadLink").html("");
$("<a></a>").
attr("href", blobURL).
attr("download", "data.csv").
text("Download Data").
appendTo('#downloadLink');
}
回答1:
The solution is to start your generated CSV with sep=;\n
.
A sample CSV will look like:
sep=;
"Product family";"Product type"
"SOJA";"product_type"
In your code you have to change 2 things to make it work.
First of all change var sep = "";
to var sep = "sep=;\n";
. And you have to change your seperator to ;
: sep = ",";
has to be sep = ";";
http://jsfiddle.net/GuyT/5KRf6/60/
回答2:
I changed the bolb data to string, so you can change all the ",":
const data = ["a", "b", "c"];
const exportData = data.toString().replace(/,/g, '\n');
const blob = new Blob([exportData], {type: 'text/csv;charset=utf-8;'});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.setAttribute('visibility', 'hidden');
link.download = 'test.csv';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
回答3:
Escape the value with this function:
function escapeVal(v) {
return '"' + v.replace('"', '""') + '"';
}
Also
sep + escapeVal($(this).val());
http://jsfiddle.net/5KRf6/51/
来源:https://stackoverflow.com/questions/22088601/how-to-change-comma-separator-to-something-else-in-blob-csv