如何将.csv中的数据加载到数据表中?

如何将.csv中的数据加载到数据表中?

问题描述:

我试图使用this table来显示包含从.csv文件加载的数据的表。如何将.csv中的数据加载到数据表中?

有没有办法将.csv中的数据加载到this table中,并且能够应用条件格式?

谢谢!

以下代码尽可能到目前为止,表格主体<tbody>与表格分开。

<!DOCTYPE html> 
<html> 

    <head> 
    <meta http-equiv="refresh" content="1000"> 
    <!-- REFRESH EVERY 2 minutes --> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    <link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css"> 
    <script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script> 
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
    <script src="http://papaparse.com/resources/js/papaparse.js"></script> 
    <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/css/demo_table.css"> 
    <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/css/jquery.dataTables.css"> 
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js"></script> 
    <style type="text/css"> 


    </style> 
    <title>HTML TABLE FROM .CSV DATA SOURCE</title> 
    </head> 

    <body> 
    <script> 


    //Setting data.csv as data source to be loaded into table id="example" 
     $(function() { 
     Papa.parse("data.csv", { 
      download: true, 
      complete: function(example) { 
      console.log("Remote file parsed!", example.data); 
      $.each(example.data, function(i, el) { 
       var row = $("<tr/>"); 
       row.append($("<td/>").text(i)); 
       $.each(el, function(j, cell) { 
       if (cell !== "") 
        row.append($("<td/>").text(cell)); 
       }); 
       $("#example tbody").append(row); 
      }); 
      } 
     }); 
     }); 

</script> 
<script type='text/javascript'> 
    //Conditionally formating. Where North office are red and South office are green 
    //<![CDATA[ 
    $(window).load(function() { 
    $('#example').dataTable({ 
     "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { 
     switch (aData[0]) { 
      case 'North': 
      $(nRow).css('color', 'red') 
      break; 
      case 'South': 
      $(nRow).css('color', 'green') 
      break; 
     } 
     } 
    }); 
    }); //]]> 

</script> 


<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%"> 
    <thead> 
    <tr> 
     <th>ID</th> 
     <th>Name</th> 
     <th>Position</th> 
     <th>Office</th> 
     <th>Extn.</th> 
     <th>Start date</th> 
     <th>Salary</th> 
    </tr> 
    </thead> 
    <tbody> 
    </tbody> 
    </table> 
    </body> 

</html> 

你必须以某种方式改变你.csv成阵列[[]]的阵列(表示列的阵列的每个元素),如在tutorial所示的页面上给出的例子。 配置对象的data键,您传递给数据表以具有此结构的值。

一个例子暴力破解转换将是这个fiddle

var csv="1,2,3\n4,5,6" 

function csvToArray(csv){ 

    return csv.split('\n').map(function(x){ 
     return x.split(','); 
}) 
}; 

console.log(csvToArray(csv)); 

为了正确解析依靠解析库。