2010-03-18 158 views
8

從YUI DataTable中獲取數據並將其轉換爲單個CSV或TSV字符串的最簡單/最快捷的方式是什麼?我基本上只是想實現一個單擊的方式來獲取整個DataTable(它應該保留當前應用的排序)爲用戶可以粘貼到電子表格中的表單。從YUI DataTable導出數據

我的DataTable可以變得相當大 - 5000到10000行,5到10列 - 效率很重要。

回答

6

怎麼是這樣的:

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]上的一些額外替換。

+0

你知道,我在那是多麼快驚訝。 – 2010-03-19 13:54:39

+0

...並保留排序。真棒! – 2010-03-19 14:01:43

+1

任何想法如何使彈出窗口打開保存/下載對話框?可能需要更改彈出文檔的內容類型等,我意識到這可能是不可能的,但如果你有辦法做到這一點,那就太好了。 – Meligy 2010-11-01 06:05:57

0

以上答案對於YUI版本3.4以上版本非常適用。但是,數據表是從版本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; 
}