使用Javascript将表格数据转换为CSV文件

时间:2019-06-05 07:29:33

标签: javascript export-to-csv

我正在尝试使用一项服务将表导出到csv,并且我想将定界符设置为以js文件中“ ~”为基础的单独列

我搜索了它,并得到一个jquery结果:

var options={"separator" : ";"};
$.csv.toArrays(csv, options);

如何在这里实现?

export_table: function(tableID, filename){
    var csv = [];
    var container = document.querySelector("#"+tableID);
    var rows = container.querySelectorAll("tr");
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        // console.log(cols);
        for (var j = 0; j < cols.length; j++)
             row.push(cols[j].innerText.replace(/\s/g, " "));   
        csv.push(row.join("~"));        
    }
    console.log(csv.join("\n"));
    // Download CSV file
    console.log(csv);
    this.downloadCSV(csv.join("\n"), filename);
},
downloadCSV: function(csv, filename) {
    var csvFile;
    var downloadLink;

    // CSV file
    csvFile = new Blob([csv], {type: "text/csv"});

    // Download link
    downloadLink = document.createElement("a");

    // File name
    downloadLink.download = filename+".xls";

    // Create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Hide download link
    downloadLink.style.display = "none";

    // Add the link to DOM
    document.body.appendChild(downloadLink);

    // Click download link
    downloadLink.click();
}

0 个答案:

没有答案