且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从CSV导入到HandsOnTable并从HandsOnTable导出到CSV

更新时间:2022-12-31 09:37:45

是的,该注释将您链接至有关操作方法的说明,并

Yup, that comment links you to the explanation on how to do it, and here is my implementation of it for anyone that wants to just reuse code. There are a few enhancements beyond the basic CSV exporting like the escaping of spaces and special characters, as well as apostrophes. It also sets the column headers if they exist so remove that line if you don't have column headers.

假设您有一个id = export-csv的按钮,相关代码:

The relevant code assuming you have a button with id=export-csv:

function parseRow(infoArray, index, csvContent) {
    var sizeData = _.size(hot1.getData());
    if (index < sizeData - 1) {
        dataString = "";
        _.each(infoArray, function(col, i) {
            dataString += _.contains(col, ",") ? "\"" + col + "\"" : col;
            dataString += i < _.size(infoArray) - 1 ? "," : "";
        })

        csvContent += index < sizeData - 2 ? dataString + "\n" : dataString;
    }
    return csvContent;
}

/**
 * Export to CSV button
 */
var exportCsv = $("#export-csv")[0];
if (exportCsv) {
    Handsontable.Dom.addEvent(exportCsv, "mouseup", function(e) {
        exportCsv.blur(); // jquery ui hackfix
        var csvContent = "data:text/csv;charset=utf-8,";
        csvContent = parseRow(colHeaders, 0, csvContent);  // comment this out to remove column headers
        _.each(hot1.getData(), function(infoArray, index) {
            csvContent = parseRow(infoArray, index, csvContent);
        });
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", $("h1").text() + ".csv");
        link.click();
    })
}

希望有帮助!