How to change “comma” separator to something else in blob csv?

拈花ヽ惹草 提交于 2019-12-25 06:55:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!