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

Serverside CSV file converting it into an JavaScript array

我正在做一个项目,我需要能够更新 HTML table,我会通过 javascript 来完成它。我还没有为这个项目创建一个 HTML 站点,因为我会尝试将 CSV 文件转换为 Java 数组,这将更新 HTML table。

我一直在尝试使用 papa parse,但它对我不起作用。我没有使用 npm 的经验,也没有像 Papa parsa 这样安装和使用东西的经验。 我找到了 this 网站,它有一个很好的将 CSV 转换为数组的功能。这个函数的一个问题是,我不能在服务器上获取本地文件,然后像处理字符串一样将其放入函数中。也许我忽略了什么?

-- 总结 -- 我想拿一个CSV文件,把它变成一个Java数组,然后把它变成一个HTML table

这是我的长 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>

我认为你最好的选择是简化一切,直到你弄清楚你到底需要什么。这是一个非常基本的工作 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,6.00 ,0.00 ,6.00 ,.80 ,5.80 ,,[=10=].00 ,[=10=].00 ,5.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 是很多事情的好工具,但是据我所知,这似乎不是一个很好的用例。

你不需要整个库来解析 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));

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

<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>