将CSV文件转换为2D数组

时间:2015-10-15 18:34:58

标签: javascript arrays

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

array[row][column]

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

我的代码的小片段,这里是完整的代码: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);
}

4 个答案:

答案 0 :(得分:9)

真实答案:使用Papa Parse。节省转义/引用字段的麻烦,包含分隔符的字段,CSV格式的变体等等......

&#34;自己做&#34;方式:csvStr.split("\n").map(function(row){return row.split(",");})

答案 1 :(得分:4)

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

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

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

<强>更新

如果您的单元格包含引号,逗号或其他转义字符,则此基本解决方案会崩溃。要解决更复杂的CSV字符串,您必须实施RegEx解决方案(请参阅How can I parse a CSV string with Javascript?的已接受答案);并且为了支持多种常见格式,你最好只使用一个库。

答案 2 :(得分:1)

逻辑类似于(但比简单)你正在做的显示结果:

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

答案 3 :(得分:1)

今天我需要这样的东西,所以我找到了最初由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;
}