Alternate title can be how to extract column names from a xlsx file. Because that is my goal.
I want to extract the column names from xlsx files, I have written code for that but the problem is for larger files having > 10k records, It is taking a lot of time and even my page hangs and is unresponsive.
extractColumnsXlsx(file: File): Promise<string[]> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = (event) => {
const arrayBuffer = event.target?.result;
try {
const workbook = XLSX.read(arrayBuffer, { type: 'array' });
const firstSheetName = workbook.SheetNames[0];
console.log("First Sheet Name:", firstSheetName);
const worksheet = workbook.Sheets[firstSheetName];
console.log("Worksheet:", worksheet);
console.log("!ref Property ->", worksheet['!ref']);
let columnNames: string[] = [];
if (worksheet['!ref']) {
const parts = worksheet['!ref'].split(':');
console.log("First and Last Cells: ", parts);
const refObj = XLSX.utils.decode_range(worksheet['!ref']);
const firstColIndex = refObj.s.c;
const lastColIndex = refObj.e.c;
console.log("firstColIndex:", firstColIndex);
console.log("lastColIndex:", lastColIndex);
let firstRowData;
try {
firstRowData = XLSX.utils.sheet_to_json(worksheet, {
header: 1,
range: `${XLSX.utils.encode_cell({ c: firstColIndex, r: 0 })}:${XLSX.utils.encode_cell({ c: lastColIndex, r: 0 })}`,
});
} catch (error) {
console.error('Error reading first row: ', error);
}
if (firstRowData && firstRowData.length) {
columnNames = firstRowData[0]; // Assuming first row contains column names (index 0)
} else {
console.warn('Failed to read column names from first row.');
}
console.log('Column Names:', columnNames);
resolve(columnNames);
} else {
console.error('Missing of invalid !ref property in worksheet!');
reject(new Error('Missing !ref property in worksheet'));
}
} catch (error) {
reject(error);
}
};
reader.onerror = (error) => reject(error);
});
}
I was searching for some method to only read the first row from the xlsx file but couldn’t find anything useful. Some one suggested using something like this
const workbook = xlsx.readFile('path/to/your/file.xlsx', { sheetRows: 5 });
but I don’t have the file path, I am taking file as an input from user using the input tag.
Himanshu Maithani is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.