Hello there!... it's already high time to talk about CSV parsing using the angular framework, this simple but powerful document serves a lot of business purposes, mainly to export a huge volume of data to a more concentrated database. and it is almost a mandatory requirement to many angular fired admin dashboards out there to get a hold of such a file to parse a tremendous amount of data and convert them to code friendly formats.
let me breakdown the whole game for you. in this table of contents.

  • What is a CSV file?
  • What is it used for?
  • npm packages for angular to handle CSV files.
  • Using papaparse on your angular app
    • Installation
    • Usage
  • Final thoughts

What is a CSV file?

CSV stands for comma separated values, a CSV file is basically a text file that has a list of data, most commonly they use the comma character to separate data. just like this...

firstname, lastname, dob,experience
Eric, John,2/12/1990,12 years
Mathew,Heyden,8/6/1993,4 years

these files can be viewed and edited in editors like the notepad or notepad++ however if the list is more complicated it could be difficult to read so you could go for a spreadsheet program like Microsoft Excel or google sheets.

What is a CSV file used for?

CSV files have a wide range of uses across different applications such as storing data to database, contact lists and much more.

Suppose a staff management application needs to upload data of 100 staff to there database, including there name, address, experience, skill sets, etc,  inputting data in a form on the application would be much time consuming and tedious, to tackle this headache someone from the team can use a word editor and prepare a clean CSV file filling in data of all the staff in a well organized tabular format. now the staff management application can have an upload CSV option where the operator can simply upload this CSV file and the app will parse the data into code friendly formats like JSON and sent it easily to the database via an API.

And if your application is built using Angular, we got you covered!

NPM Packages For Angular to Handle CSV Files.

you could find a number of CSV parser packages, common among them are ngx-papaparse, ngx-csv-parse for angular and other javascript libraries like simple-parse-csv, csv-js and much more...

in this tutorial we will use the ngx-papaparse to do the job, this library provides us with many additional options like Add quotes between all values, newline character, adding headers, etc.

Using papaparse On Your Angular App


Installation

first, let's install papaparse to your angular project,

for Angular 6+

$ npm install [email protected] --save

for Angular 8+

npm install [email protected] --save

include the papa service in your component

import { Component } from '@angular/core';
import { Papa } from 'ngx-papaparse';
 
@Component({
  ...
})
export class AppComponent {
 
    constructor(private papa: Papa) {
        const csvData = '"Hello","World!"';
        
        this.papa.parse(csvData,{
            complete: (result) => {
                console.log('Parsed: ', result);
            }
        });
    }
}

here we are using a CSV alike string named csvData and
we get the result for the parsed CSV in the "result" variable.
Now we are all set to make the UI for the CSV upload
use the below code on you component  HTML to make a super simple file upload UI  (using bootstrap 4)

<section class="content">
    <div class="row">
      <div class="col-sm-12">
        <div class="box">
          <div class="box-header">
            <div class="box-body text-center">
             
              </div>
              <input
                type="file"
                name="datasource_upload"
                class="choose-file"
                id="datasource_upload"
                accept=".xlsx,.xls,.csv"
                ngf-max-size="20MB"
                fd-input
                (change)="handleDropedFile($event)"
              />
              <p class="upload_drop_file">Choose or drop here Your CSV File.</p>
              <a
                class="dowload_csv"
                href="sample-file-link"
                download="download"
                ><i class="fa fa-download"></i> Download CSV File</a
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </section> 

some CSS for styling your UI, paste it to your components
CSS file


.choose-file:before {
  content: 'Choose or drop here Your CSV File.';
  width: 100%;
  height: 100%;
  background: #fff;
  position: absolute;
  opacity: 1 !important;
  color: #374150;
  text-align: center;
  line-height: 250px;
  font-size: 16px;

  border-radius: 10px;
  padding-left: 40px;
}

.choose-file {
  content: 'Choose or drop here Your CSV File.';
  width: 500px;
  height: 250px;
  background: #fff !important;
  position: relative;
  opacity: 1 !important;
  color: #000;
  text-align: center;
  line-height: 31px;
  font-size: 16px;
  line-height: 250px;
  border: dashed 2px #374150;
  margin: 0 auto;
}
.choose-file:after {
  content: '\f093';
  position: absolute;
  font-family: FontAwesome;
  font-size: 45px;
  left: 100px;
  top: -12px;
  color: #374150;
}

.dowload_csv {
  font-size: 14px;
  color: #000;
  text-align: center;
  margin: 10px auto;
  padding: 10px 15px;
  display: inline-block;
  border: solid 1px #374150;
  border-radius: 25px;
}
.dowload_csv:hover {
  background: #374150;
  text-decoration: none;
  color: #fff;
}

.upload_drop_file {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 161px;
  z-index: 5;
  font-size: 12px;
}

As you can see in the ts file we are using an input tag to get the CSV file. we will use the file reader API to read the file. I have given a change attribute to the input with a method named handleDropedFile($event) assigned to it.
once the user clicked on the "drop your file here" art of the UI it opens the file explorer to select the CSV file. this file will be handled by our handleDropedFile function

first, declare a variable called csvRecords as any empty array to store the data;

csvRecords = [];

let's write this function file handler function


handleDropedFile(evt) {
    this.csvRecords = [];
    this.spinner.show();
    var files = evt.target.files;  // File List object
    var file = files[0];
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = (event: any) => {
      var csv = event.target.result; // Content of CSV file
      this.papa.parse(csv, {
        skipEmptyLines: true,
        header: true,
        complete: results => {
          var data = results.data;
          this.csvRecords = data;  
          console.log(this.csvRecords);
          var total = this.csvRecords.length;
          if (total == 0) {
            this.spinner.hide();
            alert('no data in csv');
            return;
          }
      }
	}
	}

here first we are getting the file in a variable called 'file' then reading the file as text using the file reader. and then on the 'reader.onload' function we are sending the text file to papaparse, the 'results' object will now contain 3 items data,errors and meta

data: (111) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
errors: []
meta:
     delimiter: ","
     linebreak: " ↵"
     aborted: false
     truncated: false
     cursor: 17122

we get the parsed data in results.data as an array of objects,
the errors key will contain the list of errors in parsing if any,
and the meta key will contain all the metadata like delimiter, linebreak, aborted, truncated, etc

we can copy this result to our csvResult variable and use it in our application as desired.

we have made use of two options one is skipEmptyLines: true, and
header: true, which will skip empty line parsing and exclude the first line and consider it as a header whose values will be available in each object as the corresponding key in the results.data array.

Final thoughts.

I hope I was able to convey the whole concept of parsing a CSV file and reading its data on your front end in Angular if you come across any trouble achieving this feel free to drop us your query in the comment section or reach us out on our socials!

Happy coding!