Issue
I want to bind data to Table control in Angular but table is not populating with data. Table only showing static column names what I have defined in HTML. First I am fetching data from an excel file and assigning to a variable called ItemsArray
. This is my code
onFileChange(evt: any) {
const target: DataTransfer = <DataTransfer>(evt.target);
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
const wsname = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
let data = (XLSX.utils.sheet_to_json(ws, { header: 1 }));
this.ItemsArray =data
console.log(data);
reader.readAsBinaryString(target.files[0]);
}
}
This is my html code
<div>
<div style="margin: 50px auto;width: 50%;">
<h2>Please select a file: </h2>
<input type="file" (input)="onFileChange($event)" multiple="false">
</div>
<div>
<h1>Angular Table with Excel Data</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Address</th>
<th>Company</th>
<th>Skills</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of ItemsArray">
<th>{{ item.Name }}</th>
<td>{{ item.ID }}</td>
<td>{{ item.Address }}</td>
<td>{{ item.Company }}</td>
<td>{{ item.Skills }}</td>
<td>{{ item.Email }}</td>
<td>
<button type="button">Edit</button>
<button type="button">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
When I debug the code I can see data is being assigned to ItemsArray
on this line
this.ItemsArray =data
How can I fix this issue ? Should I follow other approach ?
Please find below error screenshot
Second error screenshot
My excel data but program should not be dependance to excel data.
Solution
Here is a working example!
import { Component } from '@angular/core';
import { ExcelService } from './services/excel.service';
import * as XLSX from 'xlsx';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
ItemsArray = [];
onFileChange(evt: any) {
const target: DataTransfer = <DataTransfer>evt.target;
evt.target.files[0].arrayBuffer().then((buff: ArrayBuffer) => {
let x = new Uint8Array(buff); // x is your uInt8Array
// perform all required operations with x here.
const wb: XLSX.WorkBook = XLSX.read(x, { type: 'array' });
const wsname = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
let data = XLSX.utils.sheet_to_json(ws, { header: 1 });
const [cols, ...rows]: any = data;
this.ItemsArray = rows.map((x: any) => {
const row = {};
x.forEach((x: any, i: number) => {
row[<any>cols[i]] = x;
});
return row;
});
console.log(data);
});
}
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.