代码之家  ›  专栏  ›  技术社区  ›  Matt Ball

从yui数据表导出数据

  •  8
  • Matt Ball  · 技术社区  · 15 年前

    从yui数据表中获取数据并将其转换为单个csv或tsv字符串的最简单/最快方法是什么?我基本上只想实现一种单击方式,将整个数据表(它应该保留当前应用的排序)转换成一个表单,用户可以将其粘贴到电子表格中。

    我的datatable可以非常大-5000到10000行,5到10列-所以效率很重要。

    2 回复  |  直到 12 年前
        1
  •  6
  •   Gavin Brock    15 年前

    这样怎么样:

    function dataTableAsCSV (myDataTable) {
    
        var i, j, oData, newWin = window.open(),
            aRecs = myDataTable.getRecordSet().getRecords(),
            aCols = myDataTable.getColumnSet().keys;
    
        newWin.document.write("<pre>");
    
        for (i=0; i<aRecs.length; i++) {
            oData = aRecs[i].getData();
    
            for (j=0; j<aCols.length; j++) {
                newWin.document.write( oData[aCols[j].key] + "\t");
    
            }
            newWin.document.write("\n");
    
        }
    
        newWin.document.write("</pre>n");
        newWin.document.close();
    }
    

    它将把数据表内容作为tsv呈现到一个新窗口中。它不处理包含制表符的数据,但这只是在 oData[aCols[j].key] .

        2
  •  0
  •   George Campbell    12 年前

    上面的答案对3.4版之前的yui非常有用。但是,数据表是从3.5版开始重构的。我的转换器将单元格值用双引号括起来,在单元格值中转义双引号,并处理一级列嵌套(如果存在)。

    这是一把小提琴,演示我的转换器: http://jsfiddle.net/geocolumbus/AFB3h/3/

    // Function to convert a DataTable with zero or one nested columns to CSV
    function convertToCSV(myDataTable) {
        var col,
        colIndex = 0,
            colKey,
            rowString,
            ret,
            cell,
            headerString = "";
    
        while (col = myDataTable.getColumn(colIndex++)) {
            if (col.children == null) {
                headerString += '"' + col.key + '",';
            } else {
                Y.Array.each(col.children, function (child) {
                    headerString += '"' + child.key + '",';
                });
            }
        }
        ret = headerString.replace(/,$/, '\n');
    
        Y.Array.each(myDataTable.data.toJSON(), function (item) {
            colIndex = 0;
            rowString = "";
            while (col = myDataTable.getColumn(colIndex++)) {
                if (col.children == null) {
                    cell = item[col.key].replace(/"/g, "\\\"");
                    rowString += '"' + cell + '",';
                } else {
                    Y.Array.each(col.children, function (child) {
                        cell = item[child.key].replace(/"/g, "\\\"");
                        rowString += '"' + cell + '",';
                    });
                }
            }
            ret += rowString.replace(/,$/, '') + "\n";
        });
    
        return ret;
    }