Today we are going to learn how we can load an Excel XLS file using React.

The first thing we have to do is install the xlsx library:
npm install xlsx
Once installed, we create our loading function XLSLoader:
import * as XLSX from 'xlsx';
async function loadExcelData() {
const response = await fetch('our_path_to_xls.xls');
const arrayBuffer = await response.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
const workbook = XLSX.read(data, { type: 'array' });
const sheet_name_list = workbook.SheetNames;
const jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
return jsonData;
}
loadExcelData().then(data => {
console.log(data); // Here you can do whatever you need with the data
});
Here we indicate the correct path to the file: our_path_to_xls.xls
If we want to create an independent component:
import * as XLSX from 'xlsx';
export async function loadExcelDataFunc(filePath) {
const response = await fetch(filePath);
const arrayBuffer = await response.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
const workbook = XLSX.read(data, { type: 'array' });
const sheet_name_list = workbook.SheetNames;
const jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
return jsonData;
}
And to use it:
loadExcelDataFunc('../xls/ATC_Spanish.xls').then((data) => {
console.log(data);
});
