Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  61] [ 7]  / answers: 1 / hits: 34415  / 7 Years ago, sat, october 14, 2017, 12:00:00

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' >

I can access 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);

}

How can I read cell by cell a csv file uploaded using typescript, JavaScript or jQuery? (and which is the best way to do it).


More From » jquery

 Answers
5

Here is a example implementation angular way (Angular version 2+):


@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");
}

}
}

Try it on StackBlitz


[#56228] Wednesday, October 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubreeg

Total Points: 437
Total Questions: 102
Total Answers: 102

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;