How to import CSV file into HTML form, and export

2020-07-17 05:28发布

问题:

I'm having trouble when trying to import a CSV file into an HTML form. I want the user to be able to pick a CSV file from their computer, and when they do, it will automatically fill the form for them. At the same time, if the user didn't import a file, I'd like it to be so that they can export their newly typed form into a CSV file and save it to their computer. I would really like to use javascript for this, and not PHP or a database. It doesn't seem too difficult, just don't know where to start. Thanks for answers.

回答1:

I think this will start you off. I use d3.js to parse the file.

HTML

<input id="upload" type="file">
<form id="csvForm">
    <input id="a"></input>
    <input id="b"></input>
    <input id="c"></input>
    <input id="d"></input>
</form>
<button id="download">Download</button>

JS

document.getElementById("upload").addEventListener("change", upload, false);
document.getElementById("download").addEventListener("click", download, false);

function upload(e) {
    var data = null;
    var file = e.target.files[0];

    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function (event) {
        var csvData = event.target.result;

        var parsedCSV = d3.csv.parseRows(csvData);

        parsedCSV.forEach(function (d, i) {
            if (i == 0) return true; // skip the header
            document.getElementById(d[0]).value = d[1];
        });
    }
}

function download(e) {
    data = [["id","value"]];

    var f = d3.selectAll("#csvForm > input")[0];
    f.forEach(function(d,i){
        data.push([d.id, d.value]);
    });

    var csvContent = "data:text/csv;charset=utf-8,";
    data.forEach(function (d, i) {
        dataString = d.join(",");
        csvContent += i < data.length ? dataString + "\n" : dataString;
    });

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "FormData.csv");
    link.click(); 
}

where your CSV is structured like so, with each row having a corresponding input id:

id,value
a,red
b,blue
c,green
d,yellow

http://jsfiddle.net/rg8td0Ln/5/



回答2:

Basically, CSV file is a formatted text file. You can use HTML5 File API to implement this.