Search code examples
angulartypescriptangular7xlsx

Angular 7 reading the first column of an excel file and save it into an array


I am trying to upload an excel file, where the first column is an ID column.

I need to take all the IDs and save them into an array to use them later for data management.

I am using XLSX library:

import {read, write, utils} from 'xlsx';

And for the html:

<input type="file" value="Upload Excel/CSV file" (change)="upload($event)" accept=".xlsx, .xls, .csv"/>

<button mat-fab color="warn" (click)="read()"><mat-icon color="warn">attach_file</mat-icon>Read Data</button>

I started with:

read()
{
    const file = new FileReader();
}

But I am not able to tell the file reader to read the uploaded file.

EDIT

I tried to use the change event of the file input:

upload(e)
  {
    let input = e.target;
    for (var index = 0; index < input.files.length; index++) {
        let reader = new FileReader();
        reader.onload = () => {
            // this 'text' is the content of the file
            var text = reader.result;
            console.log(reader.result)
        }

        reader.readAsText(input.files[index]);
    };
  }

But the read result is like an encryption.


Solution

  • This answer will work for .csv files :

    <input id="file" type="file" accept=".csv" (change)="fileUpload($event.target.files)">
    
    fileUpload(files) {
        if (files && files.length > 0) {
            const file: File = files.item(0);
            const reader: FileReader = new FileReader();
            reader.readAsText(file);
            reader.onload = (e) => {
                const res = reader.result as string; // This variable contains your file as text
                const lines = res.split('\n'); // Splits you file into lines
                const ids = [];
                lines.forEach((line) => {
                    ids.push(line.split(',')[0]); // Get first item of line
                });
                console.log(ids);
            };
        }
    }