0

我一直在尝试使用 Papaparse4 解析 CSV 文件,以便在使用 C3js 创建的图表上使用它,但我无法让它工作。

我希望能够加载不同的 CSV 文件,所以我使用文件输入,文件被解析(我可以在控制台上看到它),但我无法将数据加载到图表中。

你可以在这里测试它:http: //jsfiddle.net/Honzo_Nebro/mv6eomf4/

function handleFileSelect(evt) {
  var file = evt.target.files[0];

  Papa.parse(file, {
    header: true,
    dynamicTyping: true,
    complete: function(results) {
      data = results;
      console.log(data);
      var chart = c3.generate({
        bindto: '#chart',
        size: {
          height: 359
        },
        json: data,
      });
    }
  });
}

$(document).ready(function() {
  $("#csv-file").change(handleFileSelect);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv-file" name="files" />
<div id="chart"></div>

4

1 回答 1

1

因此,根据一位朋友的很多见解,我们来到了这里。它似乎不适用于这个片段,但它确实适用于 jsfiddle,我可能放错了一些东西http://jsfiddle.net/Honzo_Nebro/mv6eomf4/3/

function handleFileSelect(evt) {
  var file = evt.target.files[0];

  Papa.parse(file, {
    header: true,
    dynamicTyping: true,
    complete: function(results) {
      console.log(results.data);
      //Create an empty array and fill it with the headers
      var values = [];
      $.each(results.data[0], function(key, value) {
        values.push(key);
      });
      var chart = c3.generate({
        bindto: '#chart',
        size: {
          height: 359
        },
        data: {
          json: results.data,
          keys: {
            //assign the array to the value property
            value: values,
          },
          type: 'donut',
        },
        unload: true,
        legend: {
          postion: 'bottom',
        },
        tooltip: {
          format: {
            value: function(name, ratio, id, index) {
              ratio2 = ratio * 100;
              var text = name + ", (" + ratio2.toFixed(1) + "%)";
              return name;
            }
          }
        }
      });
    }
  });
}
<script src="https://rawgit.com/mholt/PapaParse/master/papaparse.min.js"></script>
<link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"/>
<script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv-file" name="files" />
<div id="chart"></div>

于 2015-05-08T13:11:58.677 回答