Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  163] [ 6]  / answers: 1 / hits: 25191  / 9 Years ago, fri, october 9, 2015, 12:00:00

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.


More From » html

 Answers
88

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/


[#64784] Wednesday, October 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondorlandok

Total Points: 530
Total Questions: 110
Total Answers: 96

Location: Lebanon
Member since Wed, Dec 21, 2022
1 Year ago
;