服务器端CSV文件将其转换为JavaScript数组

时间:2018-11-04 18:46:48

标签: javascript html arrays csv papaparse

我正在开发一个项目,在该项目中我需要能够更新HTML表格,并且可以通过javascript来完成。我尚未为此项目创建HTML网站,因为我会尝试将CS​​V文件转换为Java数组,从而更新HTML表。

我一直在尝试使用papa parse,但对我来说不起作用。我没有npm的安装和安装方法,例如Papa parsa。 我找到了this网站,该网站具有将CSV转换为数组的强大功能。此函数的一个问题是,我无法在服务器上获取本地文件,就无法像处理字符串一样将其放入函数中。也许我忽略了什么?

  • 我已经以某种方式使Papa Parse可以工作,但是我不知道如何在本地文件上使用它,所以我有两个工作代码,但是我不知道如何获得它们做到这一点或结果有多好。

  • 我刚得到一个随机CSV文件作为测试文件。 Normal.csv来自papa parse网站。

-总结-我要获取一个CSV文件,将其转换为Java数组,然后将其转换为HTML表

这是我的长HTML文件,其中包含所有脚本-目前没有CSS。

文件被托管在本地Apache / XAMPP服务器上。

<head>
    <title>Test af Papa Parse</title>
</head>
<body>
    <p>Hey - Test paraghaph</p>
    <script src="node_modules/papaparse/papaparse.min.js"></script> 
    <script src="node_modules/jquery/dist/jquery.min.js"></script> 
/*edit: src="http://localhost/test/node_modules/papaparse/papaparse.min.js"*/
/*edit: src="http://localhost/test/node_modules/jquery/dist/jquery.min.js"*/
    <script>    

      var config = {
        download: true,
        // rest of config ...
        delimiter: "",  // auto-detect
        newline: "",  // auto-detect
        quoteChar: '"',
        escapeChar: '"',
        header: false,
        trimHeaders: false,
        dynamicTyping: false,
        preview: 0,
        encoding: "",
        worker: false,
        comments: false,
        step: undefined,
        complete: undefined,
        error: undefined,
        download: false,
        skipEmptyLines: false,
        chunk: undefined,
        fastMode: undefined,
        beforeFirstChunk: undefined,
        withCredentials: undefined,
        transform: undefined
      }

      var data = csv2array("http://localhost/test/normal.csv")

      var data2 = Papa.parse("http://localhost/test/normal.csv", config)
      console.log("papa parsa - direktly: "+ Papa.parse("http://localhost/test/normal.csv", config))
      console.log(data)
      console.log("data2 = "+data2)
      console.log(data2);

      /**
      * Convert data in CSV (comma separated value) format to a javascript array.
       *
       * Values are separated by a comma, or by a custom one character delimeter.
       * Rows are separated by a new-line character.
       *
       * Leading and trailing spaces and tabs are ignored.
       * Values may optionally be enclosed by double quotes.
       * Values containing a special character (comma's, double-quotes, or new-lines)
       *   must be enclosed by double-quotes.
       * Embedded double-quotes must be represented by a pair of consecutive 
       * double-quotes.
       *
       * Example usage:
       *   var csv = '"x", "y", "z"\n12.3, 2.3, 8.7\n4.5, 1.2, -5.6\n';
       *   var array = csv2array(csv);
       *  
       * Author: Jos de Jong, 2010
       * 
       * @param {string} data      The data in CSV format.
       * @param {string} delimeter [optional] a custom delimeter. Comma ',' by default
       *                           The Delimeter must be a single character.
       * @return {Array} array     A two dimensional array containing the data
       * @throw {String} error     The method throws an error when there is an
       *                           error in the provided data.
       */ 
      function csv2array(data, delimeter) {
        // Retrieve the delimeter
        if (delimeter == undefined) 
          delimeter = ',';
        if (delimeter && delimeter.length > 1)
          delimeter = ',';

        // initialize variables
        var newline = '\n';
        var eof = '';
        var i = 0;
        var c = data.charAt(i);
        var row = 0;
        var col = 0;
        var array = new Array();

        while (c != eof) {
          // skip whitespaces
          while (c == ' ' || c == '\t' || c == '\r') {
            c = data.charAt(++i); // read next char
          }
          // get value
          var value = "";
          if (c == '\"') {
            // value enclosed by double-quotes
            c = data.charAt(++i);

            do {
              if (c != '\"') {
                // read a regular character and go to the next character
                value += c;
                c = data.charAt(++i);
              }
              if (c == '\"') {
                // check for escaped double-quote
                var cnext = data.charAt(i+1);
                if (cnext == '\"') {
                  // this is an escaped double-quote. 
                  // Add a double-quote to the value, and move two characters ahead.
                  value += '\"';
                  i += 2;
                  c = data.charAt(i);
                }
              }
            }
            while (c != eof && c != '\"');
            if (c == eof) {
              throw "Unexpected end of data, double-quote expected";
            }

            c = data.charAt(++i);
          }
          else {
            // value without quotes
            while (c != eof && c != delimeter && c!= newline && c != ' ' && c != '\t' && c != '\r') {
              value += c;
              c = data.charAt(++i);
            }
          }

          // add the value to the array
          if (array.length <= row) 
            array.push(new Array());
          array[row].push(value);
          // skip whitespaces
          while (c == ' ' || c == '\t' || c == '\r') {
            c = data.charAt(++i);
          }

          // go to the next row or column
          if (c == delimeter) {
            // to the next column
            col++;
          }
          else if (c == newline) {
            // to the next row
            col = 0;
            row++;
          }
          else if (c != eof) {
            // unexpected character
            throw "Delimiter expected after character " + i;
          }
          // go to the next character
          c = data.charAt(++i);
        }  
        return array;
      }
    </script>
</body>

3 个答案:

答案 0 :(得分:1)

您不需要整个库来解析CSV,这是我能想到的最简单的格式。通过ajax提取文件,然后使用以下功能之一执行CSV→数组转换。

var CSVContent = `column1, column2, column3
1, 2, hello
3, 4, world`;

function CSVToArrayOfArray(content) {
  return content
    .split('\r\n').join('\n') // CRLF -> LF
    .split('\n')
    .map(line => line.split(',').map(value => value.trim()));
}

function CSVToArrayOfObjects(content) {
  let ret = CSVToArrayOfArray(content)
    .map((arr, index, all) => {
      if (index==0) {
        return arr;
      }
      let obj = {};
      all[0].forEach((field, i) => obj[field] = arr[i])
      return obj;
    });
  ret.shift();
  return ret;
}

console.log(CSVToArrayOfArray(CSVContent));
console.log(CSVToArrayOfObjects(CSVContent));

答案 1 :(得分:0)

我认为您最好的选择是简化所有操作,直到您确切地知道需要什么为止。这是一个非常基础的Papa.parse。除非您正在做一些特别需要的配置文件,否则您不需要配置文件。这是plnkr link

<html>

  <head>
    <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.6.1/papaparse.min.js"></script>
  </head>

  <body>
    <script>
      let csvString = '2018-06-29,2018-06-29,111211,15:35:00,77,15:50:00,,Blah,Internet User,,Baln bla,0,4,0,0,0,$516.00 ,$120.00 ,$396.00 ,$19.80 ,$415.80 ,,$0.00 ,$0.00 ,$415.80';
      //let array = Papa.parse(csvString);
      //console.log(array);
     let array = Papa.parse('http://localhost/test/filename.csv',{download:true});
     console.log(array);

    </script>
  </body>

</html>

在本地服务器上完成此操作后,删除csvString,将文件加载到其中,然后从那里开始... 编辑:npm是很多事情的好工具,但是据我所知,这似乎不是一个好用例。

答案 2 :(得分:0)

最终代码。试图解释每个步骤,所以任何人都知道它是如何工作的

<head>
        <meta charset="UTF-8">
</head>
<body>
    <!--Loading Papa.parse-->
    <script src="http://localhost/test/node_modules/papaparse/papaparse.min.js"></script> 
    <!--The script-->
    <script>
        //The file with the csv data
        var CSVFile = "http://localhost/test/download.csv"

        //papa.parse function, which converts CSV file to array
        function parse() {
            Papa.parse(CSVFile,{
                download: true, //When linking an URL the download must be true
                header: true, //makes the header in front of every data in the array
                complete: function (results) { //Runs log function, with results from the conversion
                    log(results);
                }
            });         
        }
        //Papa.parse does it own callback and launches this function when done
        function log(arrayFromPapa) {
            //Writes the array in the console
            console.log(arrayFromPapa);
            //Makes the array a global array
            array = arrayFromPapa
        }
        //luanching the program
        parse()
    </script>
</body>