Home > OS >  Angular 13:How to read data from Excel?
Angular 13:How to read data from Excel?

Time:09-15

I want to display the data from a csv to the web but I get the following errors. I am using angular13.

errors

rror: src/app/app.component.html:24:11 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'select'.

24   <select [(ngModel)]="currentPage" (change)="onPageChange()">
             ~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/app.component.ts:7:16
    7   templateUrl: './app.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component AppComponent.


Error: src/app/app.component.html:24:24 - error TS2322: Type 'Event' is not assignable to type 'number'.

24   <select [(ngModel)]="currentPage" (change)="onPageChange()">
                          ~~~~~~~~~~~~~~~~~~~

  src/app/app.component.ts:7:16
    7   templateUrl: './app.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component AppComponent.


Error: src/app/app.component.ts:22:21 - error TS7006: Parameter 'e' implicitly has an 'any' type.

22   public uploadData(e) {
                       ~

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **


× Failed to compile.

import excel or csv and show data in table view

I want to do it in the following way but I can't do it locally, can you help me how to fix these errors? is it for version 13?

app.component.ts

import * as XLSX from 'xlsx';

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular '   VERSION.major;
  public tableData: any;
  public tableTitle: any;
  public customPagination = 1;
  public recordsPerPage = 10;
  public tableRecords = [];
  public pageStartCount = 0;
  public pageEndCount = 10;
  public totalPageCount = 0;
  public currentPage = 0;

  public uploadData(e) {
    console.log(e.target.files[0]);
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(<unknown>e.target);
    if (target.files.length !== 1) {
      throw new Error('Cannot use multiple files');
    }
    const reader: FileReader = new FileReader();
    reader.readAsBinaryString(target.files[0]);
    reader.onload = (e: any) => {
      /* create workbook */
      const binarystr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });

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

      /* save data */
      const data = XLSX.utils.sheet_to_json(ws); // to get 2d array pass 2nd parameter as object {header: 1}
      console.log(data); // Data will be logged in array format containing objects
      this.tableData = data;
      this.tableTitle = Object.keys(this.tableData[0]);
      this.tableRecords = this.tableData.slice(
        this.pageStartCount,
        this.pageEndCount
      );
      this.totalPageCount = this.tableData.length / this.recordsPerPage;
    };
  }

  onPageChange() {
    this.pageStartCount = this.currentPage * this.recordsPerPage;
    this.pageEndCount = this.pageStartCount   this.recordsPerPage;
    this.tableRecords = this.tableData.slice(
      this.pageStartCount,
      this.pageEndCount
    );
  }
}

app.component.html

<h1>Please upload CSV file or Excel file</h1>
<div >
  <input id="my-file-selector" type="file" (change)="uploadData($event)" name="uploadExcel" />
  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
    <path d="M0 0h24v24H0V0z" fill="none" />
    <path
      d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4 0-2.05 1.53-3.76 3.56-3.97l1.07-.11.5-.95C8.08 7.14 9.94 6 12 6c2.62 0 4.88 1.86 5.39 4.43l.3 1.5 1.53.11c1.56.1 2.78 1.41 2.78 2.96 0 1.65-1.35 3-3 3zM8 13h2.55v3h2.9v-3H16l-4-4z" />
  </svg>
  <span>Please upload file</span>
</div>
<!--pre>{{ tableData | json }}</pre-->
<table cellspacing="0" cellpadding="0">
  <tr>
    <th *ngFor="let header of tableTitle">{{ header }}</th>
  </tr>
  <tr *ngFor="let data of tableRecords; let i = index">
    <td *ngFor="let header of tableTitle">
      {{ data[header] }}
    </td>
  </tr>
</table>
<div *ngIf="totalPageCount">
  Go To Page:
  <select [(ngModel)]="currentPage" (change)="onPageChange()">
    <option *ngFor="let page of [].constructor(totalPageCount); let i = index">
      {{ i   1 }}
    </option>
  </select>
</div>

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

package.json

{
  "name": "angular-csvread",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.3.0",
    "@angular/common": "~13.3.0",
    "@angular/compiler": "~13.3.0",
    "@angular/core": "~13.3.0",
    "@angular/forms": "~13.3.0",
    "@angular/platform-browser": "~13.3.0",
    "@angular/platform-browser-dynamic": "~13.3.0",
    "@angular/router": "~13.3.0",
    "@flatfile/angular": "^3.1.1",
    "rxjs": "~7.5.0",
    "ts-xlsx": "^0.0.11",
    "tslib": "^2.3.0",
    "xlsx": "^0.18.5",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.3.8",
    "@angular/cli": "^13.0.0",
    "@angular/compiler-cli": "~13.3.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~4.0.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.1.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.6.2"
  }
}

CodePudding user response:

ngModel belongs to "FormsModule" so you need to import "FormsModule" in your app.module.

on other error TS2322: Type 'Event' is not assignable to type 'number'. your function parameter must have type onPageChange(e: Event) and <select [(ngModel)]="currentPage" (change)="onPageChange($event)">

  • Related