As displayed in answers before you need to use xlsx library. Upload the file as a static resource and import that into your component.
In my case I needed to use the xlsx.full.min.js which is the version that works alone. As all the xlsx.full.min.js files I found were encrypted I couldn't do one of the prerequisites needed which is adding to the xlsx.full.min.js the following lines "window.XLSX = XLSX;" . LWC needs this line to assign the correct context to the library.
What I did was adding window.xlsx to each call I did in my code to the library. In my case I implemented it in LWC but it should be the same in aura. Here is an example of the function that reads the xls.
import { LightningElement,track,wire } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import XLSX from '@salesforce/resourceUrl/xlsx';
export default class importxls extends LightningElement {
@track xlsxLoaded = false;
@track errorMessage = '';
connectedCallback() {
loadScript(this, XLSX)
.then(() => {
this.xlsxLoaded = true;
})
.catch(error => {
console.error('Error loading xlsx.js file: ', error);
});
}
handleFileUpload(event) {
// Get the uploaded file
const uploadedFile = event.target.files[0];
const fileType = uploadedFile.name.split('.').pop();
if(fileType === 'xls' || fileType === 'xlsx'){
// Clear the error message
this.errorMessage = '';
// Read the contents of the file
const reader = new FileReader();
reader.onload = (e) => {
// Get the binary data
const binaryData = e.target.result;
// Convert the binary data to a JavaScript object
try{
if(this.xlsxLoaded) {
const workbook = window.XLSX.read(binaryData, { type: 'binary' });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// Use the sheet_to_json method to convert the worksheet to a JavaScript object
const jsonData = window.XLSX.utils.sheet_to_json(worksheet);
console.log(jsonData);
}
}
catch(error){
console.log(error);
}
// Now you can use the jsonData to display the data in your LWC.
}
reader.readAsBinaryString(uploadedFile);
}else{
this.errorMessage = 'Invalid file type';
}
}
}
Note that this is a LWC code. The key concept is to use the context directly on your js file. Like this: