Angular tutorial: Loading Excel file with header located on row n

Is there an easy way to read specific columns from an excel file in Angular, starting from a certain row as the header? Most of the code I found involves complex scripts, and I'm looking for a simpler solution.

Below is the code I've come up with so far. It allows users to upload an excel file and displays its JSON data in the console. However, it's not capable of handling files where the header is not in the first row or reading only specified columns.

HTML:

<div class="col-md-8 form-group">    
   <input type="file" class="form-control" (change)="uploadedFile($event)" placeholder="Upload file" accept=".xlsx">
</div>

TypeScript:

import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx';  
import * as FileSaver from 'file-saver'; 

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }
  storeData: any;  
  jsonData: any;    
  fileUploaded: File;  
  worksheet: any;  

  uploadedFile(event) {  
    this.fileUploaded = event.target.files[0];  
    this.readExcel();  
  }  

  readExcel() {  
    let readFile = new FileReader();  
    readFile.onload = (e) => {  
      this.storeData = readFile.result;  
      var data = new Uint8Array(this.storeData);  
      var arr = new Array();  
      for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);  
      var bstr = arr.join("");  
      var workbook = XLSX.read(bstr, { type: "binary" });  
      var first_sheet_name = workbook.SheetNames[0];  
      this.worksheet = workbook.Sheets[first_sheet_name];  
      this.jsonData = XLSX.utils.sheet_to_json(this.worksheet, { raw: false });  
      this.jsonData = JSON.stringify(this.jsonData);  
      console.log(this.jsonData)
    }  
    readFile.readAsArrayBuffer(this.fileUploaded);  
  }
}

I'm aiming for functionality similar to pandas in Python, where specific columns can be read from an excel file:

df = pd.read_excel('fileName.xlsx', sheet_name='sheet1', header=5)
df = df[['colName1','colName2', 'colName3']].copy()

As a newcomer to Angular, I'm still navigating the basics and exploring different methods.

Answer №1

If you're looking for an easy solution, I recommend using the fantastic library called xlsx-import. You can find it at https://github.com/Siemienik/xlsx-import

This library works seamlessly with TypeScript, making it a perfect choice for your Angular application:

interface Book {
    Id: number;
    Title: string;
    Author: string;
}

const importer = new Importer(workbook);
const books: Book[] = importer.GetAllItems<Book>( {
    type: 'list',
    worksheet: 'Favourites',
    columns: [
        {
            index: 1, // column index (1,2,3....n) - started form number 1 (not 0)
            key: 'Id', // output item's field (Book.Id)
            mapper: (v: string) => Number.parseInt(v) // nullable, for transforming values
        },
        {index: 2, key: 'Title'}, // (Book.Title)
        {index: 5, key: 'Author'},  // (Book.Author)
    ],
    rowOffset: 6, //offset header row
}); 

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

What is the best way to display a JSON array in Angular 4?

Check out this JSON structure: -------------------------------------------------- "id": 2, "user": { "id": 1, "name": "User", "surname": "User", "email": "<a href="/cdn-cgi/l/email-protection" ...

Alert displayed at the center of the browser when the value surpasses the specified number

My webpage retrieves SNMP data using PHP and displays it with HTML, color-coding the values. I want to add a pop-up alert when a value exceeds a certain number. I have attempted different jQuery solutions without success. The PHP code to get the value: ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

What is the easiest way to retrieve a basic date with the month represented by a numerical

Struggling to retrieve the date in the format "Oct 29". I attempted using split but it varies every day. This is what I've come up with so far. let currentDate = new Date().toLocaleDateString('en-US', { month: 'short', day: 'n ...

When restarting the React application, CSS styles disappear from the page

While developing my React application, I encountered a problem with the CSS styling of the Select component from Material UI. Specifically, when I attempt to remove padding from the Select component, the padding is successfully removed. However, upon refre ...

Can you identify the animation being used on this button - is it CSS or JavaScript?

While browsing ThemeForest, I stumbled upon this theme: What caught my eye were the animation effects on the two buttons in the slider ("buy intense now" and "start a journey"). I tried to inspect the code using Firebug but couldn't figure it out com ...

Discovering the true nature of a generic Type in TypeScript

Consider this scenario involving TypeScript interface IApiCall<TResponse> { method: string; url: string; } Above interface is utilized in the following method; const call = <TResponse>(api: IApiCall<TResponse>): void => { ...

creating dynamic data objects in ajax calls

https://jsfiddle.net/c7n34e3x/1/ from data, data1, and data2, only data is functioning, but it lacks dynamism. This method works as intended. var settings = { "async": true, "crossDomain": true, "url": "https://domain/api/v2/playlists/", ...

My application in Angular2 is currently experiencing issues after updating npm

I'm currently facing an issue with my angular 2/cli project. After updating my npm packages, I encountered errors when using ng serve: Time: 12752ms ...

Encountering a syntax/parse error while utilizing jQuery within Velocity code

<script type="text/javascript> (function($, win) { function myCustomInit () { var self = this; var options = { 'params' : "userId=" + userId; }; self.init = function() { self.initButtonAction(); }; ...

Transitioning a NPM project to the Apache server

Recently, I successfully managed to run a simple example project by following these steps: I downloaded and installed Node.js for windows x64. I then used Git to clone the project from https://github.com/BretCameron/three-js-sample.git Next, I ran t ...

What are some ways to adjust the page being served in node.js?

I have set up my server.js file with necessary dependencies and routing for handling POST requests. However, I am looking to dynamically update the webpage served by this server when a POST request is received on /message endpoint. These requests are trigg ...

React: The error message "p is not defined" is showing up in the component file due to the no-undef

In my React application, I am looking to display a list of menu items from an array and show the detailed description of each item upon clicking. The array of menu items is stored in a separate file called dishes.js. The menu items are rendered using a Me ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Tips for refreshing views with Angular JS

I am looking to refresh all the views displayed on my page. The layout consists of a Header, Footer, and Body view. Within the Header view, there is a dropdown menu where users can choose their preferred language. Upon selecting a language, I want all the ...

Maintaining database consistency for multiple clients making simultaneous requests in Postgres with Typeorm and Express

My backend app is being built using Express, Typescript, Typeorm, and Postgres. Let's consider a table named Restaurant with columns: restaurant_id order (Integer) quota (Integer) The aim is to set an upper limit on the number of orders a restaura ...

Having trouble with AngularJS validations?

Recently, I delved into AngularJS and began experimenting with the validations included in the framework. However, I encountered an issue as the validations don't seem to function: <div class="row"> <div class="col-xs-6"> < ...

Error encountered when importing a function in Typescript causes a compiler issue

When working with Typescript, I am utilizing the import function following the instructions provided at: https://github.com/Microsoft/TypeScript/issues/12933 My implementation looks like this: import("../myScriptToBeImported").then((module) => { ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...