javascript 如何将 CSV 文件导入 HTML 表单,以及如何将 HTML 表单导出为 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33042591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import CSV file into HTML form, and export HTML form to CSV file
提问by Austin P.
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.
尝试将 CSV 文件导入 HTML 表单时遇到问题。我希望用户能够从他们的计算机中选择一个 CSV 文件,当他们这样做时,它会自动为他们填写表格。同时,如果用户没有导入文件,我希望他们可以将新输入的表单导出为 CSV 文件并将其保存到他们的计算机。我真的很想为此使用 javascript,而不是 PHP 或数据库。好像不是太难,就是不知道从何下手。感谢您的回答。
回答by Charles Clayton
I think this will start you off. I use d3.jsto parse the file.
我想这会让你开始。我使用d3.js来解析文件。
HTML
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
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:
您的 CSV 的结构如下,每一行都有一个相应的输入 ID:
id,value
a,red
b,blue
c,green
d,yellow
回答by wannadream
Basically, CSV file is a formatted text file. You can use HTML5 File APIto implement this.
基本上,CSV 文件是一种格式化的文本文件。您可以使用HTML5 文件 API来实现这一点。