从csv中读取javascript中的选定列

问题描述 投票:0回答:1

我用JavaScript上传了一个CSV文件,并做了一些清理工作,我只想显示csv文件中所有内容的1列,有什么建议吗?

这是我的JavaScript

function Upload() {
    var fileUpload = document.getElementById("fileUpload");
    var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;

    if (regex.test(fileUpload.value.toLowerCase())) {
        if (typeof (FileReader) != "undefined") {
            var reader = new FileReader();
            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 cells = rows[i].split(",");
                    if (cells.length > 1) {
                        var row = table.insertRow(-1);
                        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);
            }
            reader.readAsText(fileUpload.files[0]);
        } else {
            alert("This browser does not support HTML5.");
        }
    } else {
        alert("Please upload a valid CSV file.");
    }
}

HTML

              <input type="file" id="fileUpload" />
              <input type="button" id="upload" value="Upload" onclick="Upload()" />
              <div id="dvCSV">

任何建议将不胜感激。预先感谢。

javascript dom
1个回答
0
投票

而不是遍历所有行单元,仅输出所需的行:

var targetIndex = rows[0].indexOf("Column name");
for (var i = 0; i < rows.length; i++) {
     var cells = rows[i].split(",");
     if (cells[targetIndex]) {
          var row = table.insertRow(-1);
          var cell = row.insertCell(-1);
          cell.innerHTML = cells[targetIndex];
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.