In this article, we’ll learn how to read CSV files without any module. and that data display in the table also convert that data in JSON format to send data to the server. Let’s create a new project that you need to run following command
ng new csvread
“csvread” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go their directory. For example “cd csvread”. To Run angular applications, it required to run “ng serve”.
Let’s create a model “CsvData”. In CSV we have 4 fileds called id,min,max,score.
export class CsvData {
public id: any;
public min: any;
public max: any;
public score: any;
}
Let’s create “app.component.ts” in that we have create read CSV file function and conver json data function.
uploadListener($event: any): void {
let text = [];
let files = $event.srcElement.files;
if (this.isValidCSVFile(files[0])) {
let input = $event.target;
let reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = () => {
let csvData = reader.result;
let csvRecordsArray = (csvData).split(/\r\n|\n/);
let headersRow = this.getHeaderArray(csvRecordsArray);
this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);
};
reader.onerror = function () {
console.log('error is occured while reading file!');
};
} else {
alert("Please import valid .csv file.");
this.fileReset();
}
}
Display below is the code for the app.component.ts ,app.component.html,app.component.css
Output
Below is the full embeded code for the read CSV. you can easily used in your application.
Example