Utilizing Angular 7 to extract data from the initial column of an Excel spreadsheet and store it within an array

Currently, I am in the process of uploading an excel file that contains an ID column as its first column.

My goal is to extract all the IDs and store them in an array for future data management purposes.

To accomplish this task, I am utilizing the XLSX library:

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

For the HTML part of the code:

<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 have initiated the process with:

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

However, I am encountering difficulties instructing the file reader to read the uploaded file.

UPDATE

In an attempt to address this issue, I experimented with the change event associated with the file input:

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

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

Unfortunately, the output from the read operation appears to be encrypted.

Answer №1

Allow the library to determine how to interpret the workbook content instead of treating it as plain text.

While I am unable to verify this presently, a possible implementation could involve using an array buffer:

let reader = new FileReader();
reader.onload = function(event) {
    let data = new Uint8Array(event.target.result);
    let workbook = XLSX.read(data, {type:"array"});

    // Retrieve necessary information here
};
reader.readAsArrayBuffer(input.files[index]);

Answer №2

For those working with .csv files, the following solution can be implemented:

<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; // Store file contents
            const lines = res.split('\n'); // Split file into lines
            const ids = [];
            lines.forEach((line) => {
                ids.push(line.split(',')[0]); // Extract first item of each line
            });
            console.log(ids);
        };
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating smooth transitions between different components in Ionic 2 through animations

I have two components in my application. I am looking to create an animated transition between these pages. Specifically, I want to implement a flipping effect where page 1 transitions into page 2. Is there a plugin available for achieving this in Ionic ...

Printing the default value set in the constructor using HTML

I'm encountering an issue while trying to set a default value from the constructor parameters and display it in HTML. The error message I'm receiving is: No suitable injection token for parameter 'name' of class 'AppComponent' ...

"Efficiently Distributing HTTP Requests Among Simultaneous Observers using RxJS

Currently, I am working on a feature in my Angular application that requires handling multiple concurrent fetches for the same data with only one HTTP request being made. This request should be shared among all the subscribers who are requesting the data s ...

Fire the props.onChange() function when the TextField component is blurred

Currently, I am in the process of developing a NumberField component that has unique functionality. This component is designed to remove the default 0 value when clicked on (onFocus), allowing users to input a number into an empty field. Upon clicking out ...

Issue with Angular/Jasmine: Undefined property 'pipe' not readable

I have been struggling to resolve a problem with Angular 9, Jasmine, and RxJS without much success. While my unit tests run successfully in Jasmine, there are certain lines of code that do not get executed. Despite scouring multiple posts for assistance, ...

Potentially null object is present in a callback

The code I have is as follows: let ctx = ref.current.getContext("2d"); if(ctx){ ctx.lineWidth=1; // this line executes without errors ctx.strokeStyle=props.barStroke??"darkgray";// this line execut ...

What are some ways to enhance Rxjs syntax?

save(): void { combineLatest(this.selectedSorting$, this.selectedFilters$) .pipe( map((data) => { let obj = {}; if (data[0]) { obj['fil ...

Navigating through template files in Angular 2 components

Currently, I am working on developing a top-level component that requires an input of type @Input(): Object. This object needs to contain an array of components, which will be iterated through using *ngFor, and the templates of these components must be p ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

Issue stemming from reactivity causing difficulties with Vuex data mutation within actions

I have a Vuex store action that needs to interact with the API using new data for updating purposes. My goal is to create a separate object that mirrors an existing value in the store, allowing me to manipulate it without affecting reactivity. However, w ...

Guide to creating an Express + TypeScript API using an OpenAPI 3.0 specification

After creating specifications for my REST API server using OpenAPI 3.0, I found myself wanting to generate an expressjs app quickly instead of manually writing repetitive code. However, the generated code from editor.swagger.io is in javascript, which does ...

Encountering the issue: "Error: The mat-form-field must include a MatFormField

Working on an Angular form, attempting to validate a reactive form with Material design template. Encountering an error when trying to use ngIf condition for validation in the textbox: Error: ERROR Error: mat-form-field must contain a MatFormFieldContr ...

The Subscription request did not trigger as expected

I encountered an issue where I needed to call two services in the OnInit step, but the second request was not being sent. As a workaround, I had to call them sequentially, which I believe is not the most efficient way to write the code. (Both services on t ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

Guide to utilizing Sheet Modal in Ionic 5

In the documentation for Ionic version %, there is a showcase of the sheet modal in mobile view but the code examples do not include it. If you want to learn how to use the Sheet Modal feature, you can check out the source code under the Mobile View sectio ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

Issue encountered with Angular Material's md-chips and md-autocomplete: The error message "control.registerOnChange is not a

When attempting to wrap mat-chips and mat-autocomplete into a ControlValueAccessor, I encountered the following errors: InfoEditorComponent.html:17 ERROR TypeError: control.registerOnChange is not a function at setUpModelChangePipeline (forms.js:2701) ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

The Angular2 module x.module does not contain the exported member NavComponent

Encountering difficulties with rc.5 of Angular2. I have created an NgModule named xModule where I define NavComponent and export it. This is specified in the file x.module.ts. However, when attempting to import xModule into yModule and export NavComponent ...

Utilizing ALERTIFY JS (v1.9.0) with Angular 2: Step-by-Step Guide

I am having trouble implementing AlertifyJS (v1.9.0) in my Angular 2 application. In the vendor.ts file, I have included the following: import "alertifyjs/build/alertify.min.js"; import "alertifyjs/build/css/alertify.min.css"; and made a call to alertify ...