首页 > 解决方案 > 服务器端 CSV 文件将其转换为 JavaScript 数组

问题描述

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

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

--总结一下-- 我想获取一个 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>

标签: javascripthtmlarrayscsvpapaparse

解决方案


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


推荐阅读