Learn how to import an Excel file from an assets directory in Angular with the help of TypeScript

I hesitate to ask, but in order to solve my issue, I must seek help. My current dilemma involves reading data from an Excel file within my Angular project. This particular file is stored in the assets directory.

Although I am aware of how to access files from a folder, I seem to be encountering challenges in this scenario.

Within app.component.ts, specifically in the ngOnInit function, I attempt to fetch the file:

ngOnInit() {
  this.http.get('assets/dataTest.xlsx').subscribe((data: any) => {
    console.log("get: " + data);
  });
}

My understanding leads me to believe that the following code should be utilized within the http.get method:

const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
  console.log("READ " + e);
};
reader.readAsBinaryString(data);

However, this implementation proves to be unsuccessful as it results in an error message:

ERROR TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.

I kindly request assistance with effectively reading data from an Excel file situated within the assets directory.

Answer №1

My recommendation is to utilize a library for parsing the excel file.

Take a look at this example using SheetJs:

/* <input type="file" (change)="onFileChange($event)" multiple="false" /> */
/* ... (within the component class definition) ... */
  onFileChange(evt: any) {
    /* set up file reader */
    const target: DataTransfer = <DataTransfer>(evt.target);
    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    reader.onload = (e: any) => {
      /* read the workbook */
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});

      /* access the first sheet */
      const wsname: string = wb.SheetNames[0];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];

      /* store the data */
      this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
    };
    reader.readAsBinaryString(target.files[0]);
  }

Answer №2

Finally, I was able to resolve the issue using this solution.

read() {
this.httpClient.get('assets/files/Report DTP.xls', { responseType: 'blob' })
  .subscribe((data: any) => {
    const reader: FileReader = new FileReader();

    let dataJson1;
    let dataJson2;

    reader.onload = (e: any) => {
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

      /* grab first sheet */
      const wsname1: string = wb.SheetNames[1];
      const ws1: XLSX.WorkSheet = wb.Sheets[wsname1];

      /* grab second sheet */
      const wsname2: string = wb.SheetNames[2];
      const ws2: XLSX.WorkSheet = wb.Sheets[wsname2];

      /* save data */
      dataJson1 = XLSX.utils.sheet_to_json(ws1);
      dataJson2 = XLSX.utils.sheet_to_json(ws2);
      console.log(dataJson1);

    };
    reader.readAsBinaryString(data);
    console.log(data);
  });

}

I trust this will be beneficial to you even though it's a bit delayed :)

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

Tips for testing SSM's GetParameter with aws-sdk-client-mock in typescript

I'm looking to create a test case for the SSM GetParameterCommand request in TypeScript. Here is my code snippet: const region = "us-east-1" const awsSSMClient = new SSMClient({ region }) export async function fetchParam(parameterName: string, decry ...

A guide on setting values within a FormBuilder array

I am facing an issue with setting array values in formBuilder.array. While it is easy to set values in a regular formBuilder, I am struggling to do the same in formBuilder.array. I have tried setting values for both 'listServiceFeature' and &apos ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

Arrangements of arrays within arrays in Firebase Database

I am currently working on incorporating angulafire2 into my Angular application to access data from Firebase Database. However, I am encountering difficulties while dealing with nested arrays. The structure of my data is as follows: items{ item1{ ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Troubleshooting React TypeScript: Resolving the Error "Argument of type ''""' is not assignable to parameter of type 'SetStateAction<undefined>'"

Currently, I am troubleshooting a React application that was extracted from a live server and now I am attempting to run it on my local machine. However, upon starting up the application locally, I encountered the following error message: Argument of ty ...

Can you explain the error message 'Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser' in the IntelliJ IDEs family?

Whenever I open a .vue file in IntelliJ IDEA, I encounter the following error: Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser. The file does not match your project config: XX\XX\CurrentFile.vue. The fi ...

Is there a way to keep a button in a "pressed" state after it has been clicked?

Could someone kindly share the code with me? I am looking for a button that remains pressed after clicking it. At times, I feel embarrassed for struggling with seemingly simple tasks. Grateful for any guidance or solution provided by this community! Man ...

Creating a progressive prototype chain in TypeScript: A step-by-step guide

With JavaScript, it is possible to create a "derived class" whose "base class" is dynamic using code like the following: function NewBaseClass(sF) { function DynamicBaseClass(iF) { this.instanceField = iF; } // EDIT: oops, this is not really static i ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

When POI is used, it may result in a java.lang.NullPointerException

I am having an issue reading data from one .xlsx file and transferring it to a different file. The error occurs during the second iteration of the loop, even though all 187 rows in the first column contain data (verified). There are no blank cells, so the ...

Leveraging Angular 8's HttpClient to retrieve and display a complex JSON object in an HTML table

I am currently working with Angular 8, where I need to query an endpoint to fetch an object. Upon calling the endpoint using Advanced REST Client, I receive the following JSON response: GET: http://localhost:8090/curso_conductor/ Response: { "dato": [ ...

I am looking to integrate Firebase app-check into my Angular 12 application. Can anyone guide me on

I have attempted the suggestions provided in this particular inquiry Here is the code snippet I am working with: // firebase-init.ts import firebase from 'firebase/app'; import 'firebase/app-check'; import { environment } from ' ...

Angular 2/4 - Saving User Object Information in the Front-End Instead of Repeatedly Contacting the Back-End Server

Is there a more efficient way to store and update the current user details in the frontend, without constantly making new HTTP GET requests to the backend every time a new component loads? The solution I came up with is a UserService class that handles se ...

Omit the element that disrupts the functionality of Angular Universal

Utilizing ng-toolkit in conjunction with ng add @ng-toolkit/universal proved to successfully integrate Angular Universal support into my project. After building the production version without encountering any errors and running the server seamlessly, I fa ...

Is it possible to access 'import.meta' only within a module in an Angular micro front-end setup?

I have been incorporating mfe (module federation microfrontend) into my Angular project. However, I encountered an error in the console when trying to load the remoteEntry.js file: import.meta outside a module The version of Angular that I'm using is ...

Running Ng serve is not functioning properly with no indications of errors or messages to identify the issue

Recently, after updating to MacOS Sonoma, I encountered an issue where the ng serve command stopped working. While ng version is still functional and displays the current version, running ng serve in my project doesn't yield any results. The terminal ...

Extract the ID from the Router's URL

I am currently working on a project where I need to keep a log of every page that is accessed in my Angular application. Here is an overview of my routing setup: const routes: Routes = [ { path: ':id', component: AppComponent} ]; Within my a ...

Expanding the current @types type definition to encompass additional properties that are currently absent

Currently, I am utilizing the most recent @types for leaflet in my project (v1.2.5), however, they do not align with the latest version of leaflet (1.3.x). Specifically, their LayerGroup interface lacks a setZIndex property which I need to include by exte ...

Passing a variable from the second child component to its parent using Angular

Need help with passing variables between two child components Parent Component: deposit.component.html <div> <app-new-or-update-deposit [(isOpenedModal)]="isOpenedModal"></app-new-or-update-deposit> </div> Deposit Component ...