I need to get data from an excel file using Angular and display it on the webpage. I already have the excel file and all its data. I want to add it to my project folder and read data from it and display it. Any ideas or suggestions on how to do that will be highly appreciated. Thanks in advance.
2 Answers
import follow import { read, utils } from "xlsx";
in file uploader call follow method for onFileChange event
onFileChange(event) {
if (event.target.files.length > 0) {
this.file = event.target.files[0];
this.uploadEvent = event;
}
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.arrayBuffer = fileReader.result;
var data = new Uint8Array(this.arrayBuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i)
arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = read(bstr, {
type: "binary"
});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
this.exceljsondata = utils.sheet_to_json(worksheet, {
raw: true,
defval: "",
});
};
fileReader.readAsArrayBuffer(this.file);
}
- then all datas stored in 'exceljsondata' as json array now you can just access data as normal json array
Comments
import follow import { read, utils } from "xlsx";
in file uploader call follow method for onFileChange event
onFileChange(event) {
if (event.target.files.length > 0) {
this.file = event.target.files[0];
this.uploadEvent = event;
}
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.arrayBuffer = fileReader.result;
var data = new Uint8Array(this.arrayBuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i)
arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = read(bstr, {
type: "binary"
});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
this.exceljsondata = utils.sheet_to_json(worksheet, {
raw: true,
defval: "",
});
};
fileReader.readAsArrayBuffer(this.file);
}
- html file should be as follows
<div class="form-group row">
<label class="col-sm-12 col-form-label"> Excel file to upload</label>
<div class="col-sm-12">
<input type="file" formControlName="orderFile" class="form-control inputFile" accept=".xls, .xlsx"
(change)="onFileChange($event);" [ngClass]="{ 'is-invalid': submitted && f.orderFile.errors }">
<span *ngIf="f.orderFile.errors?.required && submitted">File is Required</span>
</div>
</div>
- then all datas stored in 'exceljsondata' as json array now you can just access data as normal json array