如何逐行读取angular2上的csv文件 [英] How to read a csv file on angular2 line by line
本文介绍了如何逐行读取angular2上的csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用angular2编写一个应用程序,该应用程序只需在html中输入一个即可读取csv文件:
I am programming an application in angular2 that reads a csv file with a simply input in html:
<input type='file' name='userFile' id='file' >
我可以访问component.ts上的文件:
I can acces to the file at the component.ts:
ngOnInit() {
var input = (<HTMLInputElement>document.getElementById("file"));
input.addEventListener("change", function(event) {
var files = input.files;
var len = files.length;
if (len) {
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
}
}, false);
}
如何逐个阅读使用打字稿,JavaScript或jquery上传的csv文件? (而这是最好的方法).
How can I read cell by cell a csv file uploaded using typescript, javascript or jquery? (and wich is the best way to do it).
推荐答案
以下是角度实现的示例:
Here is a example implementation angular way:
@Component({
selector: 'app-my-file',
template: `
<div class="form-group">
<input type="file" (change)="onFileSelect($event.target)" name="myfile">
</div>
`,
styles: [``]
})
export class YourComponent implements OnInit {
csvContent: string;
constructor(){}
ngOnInit(){
}
onFileLoad(fileLoadedEvent) {
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
// alert(this.csvContent);
}
onFileSelect(input: HTMLInputElement) {
const files = input.files;
var content = this.csvContent;
if (files && files.length) {
/*
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
*/
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.readAsText(fileToLoad, "UTF-8");
}
}
}
这篇关于如何逐行读取angular2上的csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文