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.