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

后端 未结 13 783
不知归路
不知归路 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:07

    Here's a JavaScript function that parses CSV data, accounting for commas found inside quotes.

    // Parse a CSV row, accounting for commas inside quotes                   
    function parse(row){
      var insideQuote = false,                                             
          entries = [],                                                    
          entry = [];
      row.split('').forEach(function (character) {                         
        if(character === '"') {
          insideQuote = !insideQuote;                                      
        } else {
          if(character == "," && !insideQuote) {                           
            entries.push(entry.join(''));                                  
            entry = [];                                                    
          } else {
            entry.push(character);                                         
          }                                                                
        }                                                                  
      });
      entries.push(entry.join(''));                                        
      return entries;                                                      
    }
    

    Example use of the function to parse a CSV file that looks like this:

    "foo, the column",bar
    2,3
    "4, the value",5
    

    into arrays:

    // csv could contain the content read from a csv file
    var csv = '"foo, the column",bar\n2,3\n"4, the value",5',
    
        // Split the input into lines
        lines = csv.split('\n'),
    
        // Extract column names from the first line
        columnNamesLine = lines[0],
        columnNames = parse(columnNamesLine),
    
        // Extract data from subsequent lines
        dataLines = lines.slice(1),
        data = dataLines.map(parse);
    
    // Prints ["foo, the column","bar"]
    console.log(JSON.stringify(columnNames));
    
    // Prints [["2","3"],["4, the value","5"]]
    console.log(JSON.stringify(data));
    

    Here's how you can transform the data into objects, like D3's csv parser (which is a solid third party solution):

    var dataObjects = data.map(function (arr) {
      var dataObject = {};
      columnNames.forEach(function(columnName, i){
        dataObject[columnName] = arr[i];
      });
      return dataObject;
    });
    
    // Prints [{"foo":"2","bar":"3"},{"foo":"4","bar":"5"}]
    console.log(JSON.stringify(dataObjects));
    

    Here's a working fiddle of this code.

    Enjoy! --Curran

    0 讨论(0)
  • 2020-11-22 01:07

    Actually you can use a light-weight library called any-text.

    • install dependencies
    npm i -D any-text
    
    • use custom command to read files
    var reader = require('any-text');
     
    reader.getText(`path-to-file`).then(function (data) {
      console.log(data);
    });
    

    or use async-await :

    var reader = require('any-text');
     
    const chai = require('chai');
    const expect = chai.expect;
     
    describe('file reader checks', () => {
      it('check csv file content', async () => {
        expect(
          await reader.getText(`${process.cwd()}/test/files/dummy.csv`)
        ).to.contains('Lorem ipsum');
      });
    });
    
    0 讨论(0)
  • 2020-11-22 01:08
    $(function() {
    
          $("#upload").bind("click", function() {
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx)$/;
                if (regex.test($("#fileUpload").val().toLowerCase())) {
                  if (typeof(FileReader) != "undefined") {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var customers = new Array();
                        var rows = e.target.result.split("\r\n");
                        for (var i = 0; i < rows.length - 1; i++) {
                          var cells = rows[i].split(",");
                          if (cells[0] == "" || cells[0] == undefined) {
                            var s = customers[customers.length - 1];
                            s.Ord.push(cells[2]);
                          } else {
                            var dt = customers.find(x => x.Number === cells[0]);
                            if (dt == undefined) {
                              if (cells.length > 1) {
                                var customer = {};
                                customer.Number = cells[0];
                                customer.Name = cells[1];
                                customer.Ord = new Array();
    
                                customer.Ord.push(cells[2]);
                                customer.Point_ID = cells[3];
                                customer.Point_Name = cells[4];
                                customer.Point_Type = cells[5];
                                customer.Set_ORD = cells[6];
                                customers.push(customer);
                              }
                            } else {
                              var dtt = dt;
                              dtt.Ord.push(cells[2]);
    
                            }
                          }
                        }
    
    0 讨论(0)
  • 2020-11-22 01:10

    I am using d3.js for parsing csv file. Very easy to use. Here is the docs.

    Steps:

    • npm install d3-request

    Using Es6;

    import { csv } from 'd3-request';
    import url from 'path/to/data.csv';
    
    csv(url, function(err, data) {
     console.log(data);
    })
    

    Please see docs for more.

    Update - d3-request is deprecated. you can use d3-fetch

    0 讨论(0)
  • 2020-11-22 01:12
    function CSVParse(csvFile)
    {
        this.rows = [];
    
        var fieldRegEx = new RegExp('(?:\s*"((?:""|[^"])*)"\s*|\s*((?:""|[^",\r\n])*(?:""|[^"\s,\r\n]))?\s*)(,|[\r\n]+|$)', "g");   
        var row = [];
        var currMatch = null;
    
        while (currMatch = fieldRegEx.exec(this.csvFile))
        {
            row.push([currMatch[1], currMatch[2]].join('')); // concatenate with potential nulls
    
            if (currMatch[3] != ',')
            {
                this.rows.push(row);
                row = [];
            }
    
            if (currMatch[3].length == 0)
                break;
        }
    }
    

    I like to have the regex do as much as possible. This regex treats all items as either quoted or unquoted, followed by either a column delimiter, or a row delimiter. Or the end of text.

    Which is why that last condition -- without it it would be an infinite loop since the pattern can match a zero length field (totally valid in csv). But since $ is a zero length assertion, it won't progress to a non match and end the loop.

    And FYI, I had to make the second alternative exclude quotes surrounding the value; seems like it was executing before the first alternative on my javascript engine and considering the quotes as part of the unquoted value. I won't ask -- just got it to work.

    0 讨论(0)
  • 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);
    <input type="file" id="file-input" />
    
    <h3>Raw contents of the file:</h3>
    <pre id="file-content">No data yet.</pre>
    
    <h3>Parsed file contents:</h3>
    <pre id="file-parsed">No data yet.</pre>

    0 讨论(0)
提交回复
热议问题