How to read data From *.CSV file using javascript?

后端 未结 13 791
不知归路
不知归路 2020-11-22 00:46

My csv data looks like this:

heading1,heading2,heading3,heading4,heading5,value1_1,value2_1,value3_1,value4_1,value5_1,value1_2,value2_2,value3_2,val

13条回答
  •  温柔的废话
    2020-11-22 01:14

    If you want to solve this without using Ajax, use the FileReader() Web API.

    Example implementation:

    1. Select .csv file
    2. See output

    function readSingleFile(e) {
      var file = e.target.files[0];
      if (!file) {
        return;
      }
    
      var reader = new FileReader();
      reader.onload = function(e) {
        var contents = e.target.result;
        displayContents(contents);
        displayParsed(contents);
      };
      reader.readAsText(file);
    }
    
    function displayContents(contents) {
      var element = document.getElementById('file-content');
      element.textContent = contents;
    }
    
    function displayParsed(contents) {
      const element = document.getElementById('file-parsed');
      const json = contents.split(',');
      element.textContent = JSON.stringify(json);
    }
    
    document.getElementById('file-input').addEventListener('change', readSingleFile, false);
    
    
    

    Raw contents of the file:

    No data yet.

    Parsed file contents:

    No data yet.

提交回复
热议问题