0

I used a javascript to upload a csv file and did some cleaning, I would like to only show 1 column out of everything in the csv file, any advice?

Here is my 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">

Any advice will be greatly appreciated. Thanks in advance.

1
  • Why don't you use external CSV libraries that are browser compatible? There is no need to reinvent the wheel. Commented May 16, 2020 at 15:29

1 Answer 1

1

Instead of iterating over all the row cells, just output the one you want:

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];
     }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.