xlsx
Basic start up
https://www.npmjs.com/package/xlsx
- If you are using nodejs
Terminal
npm i xlsx
- If you are using react / HTML not nodejs environment…
Terminal
npm i https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
1. Read file to JSON array (Nodejs)
server.ts
async function readFile(i:number): object[] {
const workbook = XLSX.readFile('004.xlsx'); // Sheet path
const first_worksheet = workbook.Sheets[workbook.SheetNames[i]]; // Which work sheet
const data = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });
return data;
}
2. Read file to JSON array (React.js / HTML)
xlsxUtils.ts
import XLSX from "xlsx";
async function readFileToBuffer(inputFile: File): Promise<Uint8Array> {
return new Promise((rec) => {
let reader = new FileReader();
reader.onload = function () {
const arrayBuffer = new Uint8Array(reader.result as ArrayBuffer);
rec(arrayBuffer);
};
reader.readAsArrayBuffer(inputFile);
});
}
// https://docs.sheetjs.com/docs/api/utilities/array#array-output
export async function readXlsxFileToJsonScheme(inputFile: File) {
try {
const arrayBuffer = await readFileToBuffer(inputFile);
// Convert the Excel buffer to a workbook
const workbook = XLSX.read(arrayBuffer, {
type: "array",
cellDates: true,
dateNF: 'dd"/"mm"/"yyyy',
// raw: true
});
// Get the first sheet
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
// Convert the sheet data to JSON
const jsonData: any = XLSX.utils.sheet_to_json(sheet, {
header: 1,
blankrows: false,
defval: null,
raw: false
});
// Map the array to an array of objects
const resultArray = jsonData.map((row: any) => {
const obj = {} as any;
for (let i = 0; i < jsonData[0].length; i++) {
obj[jsonData[0][i]] = row[i];
}
return obj;
});
const noHeaderLs = resultArray.slice(1);
return noHeaderLs;
} catch (error) {
console.log(error);
}
}