簡體   English   中英

服務器端CSV文件將其轉換為JavaScript數組

[英]Serverside CSV file converting it into an JavaScript array

我正在開發一個項目,在該項目中我需要能夠更新HTML表,並且可以通過javascript來完成。 我尚未為此項目創建HTML網站,因為我會嘗試將CS​​V文件轉換為Java數組,從而更新HTML表。

我一直在嘗試使用papa parse,但是對我來說不起作用。 我沒有npm的安裝和安裝方法,例如Papa parsa。 我找到了這個網站,它具有將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>

您不需要整個庫即可解析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)); 

我認為您最好的選擇是簡化所有操作,直到您明確需要什么為止。 這是一個非常基礎的Papa.parse。 除非您正在做一些特別需要的配置文件,否則您不需要配置文件。 這是一個plnkr鏈接

<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是很多事情的好工具,但是據我所知,這似乎並不就像一個很好的用例。

最終代碼。 試圖解釋每個步驟,所以任何人都知道它是如何工作的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM