javascript 将 CSV 文件转换为二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33155999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:10:53  来源:igfitidea点击:

Converting a CSV File Into a 2D Array

javascriptarrays

提问by Mees van Z

How can i convert the data inside an CSV file to a 2d array?

如何将 CSV 文件中的数据转换为二维数组?

array[row][column]

I already have an upload script that will display all the data inside a CSV file.

我已经有一个上传脚本,它将显示 CSV 文件中的所有数据。

Little snippet of my code, here's the full code: http://jsfiddle.net/Meesz/wj6q7c30/

我的代码的一小段,这里是完整的代码:http: //jsfiddle.net/Meesz/wj6q7c30/

reader.onload = function (e) {
  var table = document.createElement("table");
  var rows = e.target.result.split("\n");
  for (var i = 0; i < rows.length; i++) {
    var row = table.insertRow(-1);
    var cells = rows[i].split(",");
    for (var j = 0; j < cells.length; j++) {
        var cell = row.insertCell(-1);
        cell.innerHTML = cells[j];
    }
  }
  var dvCSV = document.getElementById("dvCSV");
  dvCSV.innerHTML = "";
  dvCSV.appendChild(table);
}

回答by Fabio Beltramini

Real answer: Use Papa Parse. Save yourself the hassle of escaped/quoted fields, fields with delimiters in them, variations in the CSV format, etc...

真正的答案:使用Papa Parse。省去转义/引用字段、带有分隔符的字段、CSV 格式的变体等的麻烦...

The "do it yourself" way: csvStr.split("\n").map(function(row){return row.split(",");})

“自己动手”的方式: csvStr.split("\n").map(function(row){return row.split(",");})

回答by gfullam

Use String.split()and Array.map()

使用String.split()Array.map()

Because "the map()method creates a new array with the results of calling a provided function on every element in this array" (source: MDN), it is ideally suitedsomewhat suitablefor creating a two dimensional array from a very basicCSV string that has already been converted into an array via the split()method.

因为“该map()方法创建了一个新数组,其结果是对该数组中的每个元素调用提供的函数” (来源:MDN,因此非常适合有点适合非常基本的CSV 字符串创建二维数组,该字符串已经通过split()方法转换为数组。

function csvToArray (csv) {
    rows = csv.split("\n");

    return rows.map(function (row) {
     return row.split(",");
    });
};

// Hard-coded for brevity, but you can set this variable with FileReader
var csv = "the,quick,brown,fox\n" +
          "jumps,over,the,lazy,dog";

var array = csvToArray(csv);

console.log(array);
Open your console.

Update:

更新:

This basic solution falls apart if your cells contain quotes, commas or other escaped characters. To address more complex CSV strings, you'd have to implement a RegEx solution (see accepted answer to How can I parse a CSV string with Javascript?); and to support multiple common formats, you'd be better off just using a library.

如果您的单元格包含引号、逗号或其他转义字符,则此基本解决方案会失效。要处理更复杂的 CSV 字符串,您必须实施 RegEx 解决方案(请参阅如何使用 Javascript 解析 CSV 字符串?);并且要支持多种常见格式,最好只使用一个库。

回答by Paul Roub

The logic is similar to (but simpler than) what you're already doing to display the results:

逻辑类似于(但比)您已经为显示结果所做的操作:

var data = [];
var rows = e.target.result.split("\n");

for (var i = 0; i < rows.length; i++) {
  var cells = rows[i].split(",");
  data.push( cells );
}

var data = [];
var csv = "one,two,three\n" +
          "four,five,six";

var rows = csv.split("\n");

for (var i = 0; i < rows.length; i++) {
  var cells = rows[i].split(",");
  data.push( cells );
}

console.dir(data);

回答by Gregory Nowakowski

I needed something like this today so I found snippet originally done by by Bennadel and cleaned it up a bit also adding in edge cases.

我今天需要这样的东西,所以我找到了最初由 Bennadel 完成的片段,并对其进行了一些清理,同时还添加了边缘情况。

/*
 *  shortened version of:
 *   http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
 *
 *  Supports columns that are quoted/non-quoted. Takes care of quoted columns that may also have \n's inside
 *  them instead of using a naive approach of split('\n')
 *
 *  @param csvString {string} CSV file of rows separated by new lines.  
 *  @param delimiter {string} delimiter used to split columns 
 *
 *  return {rows} Array of rows with columns containing parsed CSV data
 */

function CSVParse(csvString, delimiter = ",") {

  if (!csvString || !csvString.length)
    return [];

  const pattern = new RegExp(
   ( "(\" + delimiter + "|\r?\n|\r|^)" +
     "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
     "([^\"\" + delimiter + "\r\n]*))"
   ), "gi"
  );

  let rows = [[]]; 
  let matches = false;

  while (matches = pattern.exec(csvString)) {

    const matched_delimiter = matches[1];
    const matched_cellQuote = matches[2];
    const matched_cellNoQuote = matches[3];

    /*
     * Edge case: Data that starts with a delimiter
     */
    if (matches.index == 0 && matched_delimiter)
      rows[rows.length - 1].push("");

    /*
     * Fix empty lines
     */
    if(!matches[2] && !matches[3])
      continue;

    if (matched_delimiter.length && matched_delimiter !== delimiter)
      rows.push([]);

    const matched_value = (matched_cellQuote)
      ? matched_cellQuote.replace(
          new RegExp("\"\"", "g"), "\""
        )
      : matched_cellNoQuote;

    rows[rows.length - 1].push(matched_value);

   }

   return rows;
}