简体   繁体   English

使用 D3.js 解析上传的 CSV 文件

[英]Parse Uploaded CSV file using D3.js

I'm new to d3.js so I know this might seem as a silly question to some so please bear with me.我是 d3.js 的新手,所以我知道这对某些人来说可能是一个愚蠢的问题,所以请多多包涵。 I'm trying to parse a csv file which a user uploads and print it's output in the console.我正在尝试解析用户上传的 csv 文件并在控制台中打印它的 output 。 I'm able to parse the CSV file when I provide the absolute path of the CSV file but when I try doing the same with file upload functionality I'm not getting any output in the console..当我提供 CSV 文件的绝对路径时,我能够解析 CSV 文件,但是当我尝试对文件上传功能执行相同操作时,我在控制台中没有得到任何 Z78E6221F6393D1356681DB398F14CE6D。

Working Javascript Code ..工作 Javascript 代码..

    var dataset = [];
    d3.csv("sample.csv", function(data) {
    dataset = data.map(function(d) { return [ d["Title"], d["Category"], d["ASIN/ISBN"], d["Item Total"] ]; });
    console.log(dataset[0]);
    console.log(dataset.length);
    }); 

Console Output ...控制台 Output ...

["Men's Brooks Ghost 8 Running Shoe Black/High Risk Red/Silver Size 11.5 M US", "Shoes", "B00QH1KYV6", "$120.00 "]
 8

New HTML code ..新 HTML 代码..

    <input type="file" id="csvfile" name="uploadCSV"/>
    <br/>
    <button onclick="howdy()">submit</button>

Modified Javascript Code(not working) ..修改 Javascript 代码(不工作) ..

    var myfile = $("#csvfile").prop('files')[0];
    var reader = new FileReader();

    reader.onload = function(e) {
    var text = reader.result;
    }

    reader.readAsDataURL(myfile);

     var dataset = [];
    d3.csv(reader.result , function(data) {
    dataset = data.map(function(d) { return [ d["Title"], d["Category"], d["ASIN/ISBN"], d["Item Total"] ]; });
    console.log(dataset[0]);
    console.log(dataset.length);
    })

Since there was no official documentation on how to handle user uploaded CSV file I can't figure out where I'm going wrong..Is there a way I can use HTML5 file reader??由于没有关于如何处理用户上传的 CSV 文件的官方文档,我无法弄清楚我哪里出错了。有没有办法可以使用 HTML5 文件阅读器? Please help..请帮忙..

You are close but you don't need to and can't call d3.csv on a reader.result. 您已经很近了,但是您不需要,也不能在d3.csv上调用d3.csv。 d3.csv makes an async AJAX call to retrieve a CSV file from a server. d3.csv进行异步AJAX调用,以从服务器检索CSV文件。 You already have the file contents and just want to parse, so use d3.csv.parse . 您已经有了文件内容,只想解析,因此请使用d3.csv.parse

Full working example: 完整的工作示例:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> </head> <body> <input type="file" onchange="loadFile()" /> <script> var reader = new FileReader(); function loadFile() { var file = document.querySelector('input[type=file]').files[0]; reader.addEventListener("load", parseFile, false); if (file) { reader.readAsText(file); } } function parseFile(){ var doesColumnExist = false; var data = d3.csv.parse(reader.result, function(d){ doesColumnExist = d.hasOwnProperty("someColumn"); return d; }); console.log(doesColumnExist); } </script> </body> </html> 

This is for d3-csv@3这是用于d3-csv@3

 <!-- https://www.jsdelivr.com/package/npm/d3-dsv --> <script src="https://cdn.jsdelivr.net/npm/d3-dsv@3.0.1/dist/d3-dsv.min.js" integrity="sha256-IrzYc2a3nTkfvgAyowm/WKmIGdVCMCcccPtz+Y2y6VI=" crossorigin="anonymous"></script> <input type="file" accept=".csv"> <button>test button</button> <script> const testData = `owner,repo,"branch name" foo,demo,master boo,"js awesome",sha1123456 ` document.querySelector(`input`).onchange = async e => { const input = e.target const file = input.files[0] const reader = new FileReader() reader.readAsText(new Blob( [file], {"type": file.type} )) const fileContent = await new Promise(resolve => { reader.onloadend = (event) => { resolve(event.target.result) } }) const csvData = d3.csvParse(fileContent) console.log(csvData) } document.querySelector(`button`).onclick = e => { const csvData = d3.csvParse(testData) console.log(csvData) } </script>


The below link may help you know the implementation of csvParse下面的链接可以帮助您了解csvParse的实现


If you just load the CSV only then do not import the whole JS.如果您只加载 CSV,则不要导入整个 JS。 (instead of the d3-csv.js ) (而不是d3-csv.js

https://cdn.jsdelivr.net/npm/d3@7.0.1/dist/d3.min.js https://cdn.jsdelivr.net/npm/d3@7.0.1/dist/d3.min.js

https://cdn.jsdelivr.net/npm/d3-dsv@3.0.1/dist/d3-dsv.min.jshttps://cdn.jsdelivr.net/npm/d3-dsv@3.0.1/dist/d3-dsv.min.js

This is an old question and I think we have to clarify some points.这是一个老问题,我认为我们必须澄清一些观点。

  1. How to load a local csv file如何加载本地 csv 文件
  2. How to link the loaded file with D3如何将加载的文件与 D3 链接

1. Load a file is very simple just check this example: 1.加载文件非常简单,只需检查这个例子:

 const fileInput = document.getElementById('csv') const readFile = e => { const reader = new FileReader() reader.onload = () => { document.getElementById('out').textContent = reader.result } reader.readAsBinaryString(fileInput.files[0]) } fileInput.onchange = readFile
 <div> <p>Select local CSV File:</p> <input id="csv" type="file" accept=".csv"> </div> <pre id="out"><p>File contents will appear here</p></pre>

Here we have a simple input element with type="file" attribute, this lets us to pick a csv file.这里我们有一个type="file"属性的简单input元素,这让我们可以选择一个 csv 文件。 Then the readFile() function will be triggered whenever a file is selected and will call the onload function after reading the file as a binary string. Then the readFile() function will be triggered whenever a file is selected and will call the onload function after reading the file as a binary string.

2. I recommend to use readAsDataURL() to integrate it with d3 like this: 2. 我建议使用readAsDataURL()将其与 d3 集成,如下所示:

 const fileInput = document.getElementById('csv') const previewCSVData = async dataurl => { const d = await d3.csv(dataurl) console.log(d) } const readFile = e => { const file = fileInput.files[0] const reader = new FileReader() reader.onload = () => { const dataUrl = reader.result; previewCSVData(dataUrl) } reader.readAsDataURL(file) } fileInput.onchange = readFile
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <div> <p>Select local CSV File:</p> <input id="csv" type="file" accept=".csv"> </div> <pre id="out"><p>File contents will appear here</p></pre>

To integrate the loaded file we call previewCSVData() and pass the file then we parse it using d3.csv() method.为了集成加载的file ,我们调用previewCSVData()并传递file ,然后我们使用d3.csv()方法对其进行解析。 Also lets use await because it is an asynchronous call.也让我们使用 await 因为它是一个异步调用。

Note:笔记:

d3.csv internally uses fetch and works for any type of URL, ( httpURL , dataURL , blobURL , etc...) d3.csv内部使用fetch并适用于任何类型的 URL,( httpURLdataURLblobURL等......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM