HOW TO UPLOAD AND READ XLSX FILE
May 13, 2022 Copy Link
السلام عليكم 👋
النهارده هنشوف إزاي نرفع و نقرأ فايل XLSX بإستخدام الجافا إسكربت 📄
آخر بروجكت إشتغلت عليه كان مطلوب مني أرفع و أقرأ فايل XLSX و أعرضه في جدول عشان يظهر لليوزر, الفايل دا بيكون فيه بيانات الطلاب و عملت سيرش و لقيت sheetJS, و الموضوع كان مُتغير بشكل كبير لأن لكل صف دراسي مواد خاصة بيه و لكل مادة الدرجة الخاصة بيها فا كان لازم أعمل حاجة مُخترمة تمشي مع الموضوع دا, برضو كان لكل درجة حد أقصي فا كان لازم أشيك علي كل الدرجات اللي بقرأها من الفايل بحيث إنها تكون أقل من أو تساوي الحد الأقصي فا تعالوا كدا نشوف الكود شكله هيبقي عامل إزاي 🤔
var yourColumnsNames = ["name", "arabic", "english", "art", "music"];
var maxDegrees = [20, 30, 30, 15];
أولاً كدا دول المُتغيرات اللي هستخدمهم في كل شغلي, أول مُتغير دا فيه أسماء الأعمده اللي متوقع إنها تكون موجودة في الفايل, و تاني مُتغير دا فيه الحد الأقصي لكل درجة موجودة في الفايل, طبعاً البيانات دي بتكون متخزنة علي السيستم من خلال الأدمن 🤴
function setStudentMarksDataRow(rowNumber, currentRow = null) { var body = null, column = 0;
const prefix = `<tr id="student_row_data_${rowNumber}"><td><label>${rowNumber} </label><td><td><input type="text" class="form-control" name="students_names[]" style="width:400px;" value="${currentRow ? currentRow[yourColumnsNames[column]] : ''}"></td>`; column += 1; // `-1` to exclude the `name` column for (; column < yourColumnsNames.length - 1; column++) { body += `<td><input type="number" class="form-control input_mark_${rowNumber}" name="marks[]" value="${currentRow ? currentRow[yourColumnsNames[column]] : ''}" min="0" onchange="checkInputMaxDegree(${rowNumber});"></td>`; }
return `${prefix}${body}<td><input type="number" class="form-control" id="marks_sum_${rowNumber}" name="marks[]" value="${currentRow ? currentRow[yourColumnsNames[column]] : ''}" min="0" readonly></td></tr>`; }
ثانياً الدالة دي من خلالها بقرأ كل صف في الفايل و بعرضه في جدول عشان يظهر لليوزر 👇
function getMarksSum(rowNumber) {
var marksInputs = document.getElementsByClassName(`input_mark_${rowNumber}`);
var marksSum = 0;
for (var i = 0; i < marksInputs.length; i++) {
var currentValue = isNaN(parseInt(marksInputs[i].value)) ? 0 : parseInt(marksInputs[i].value);
marksSum += currentValue;
}
document.getElementById(`marks_sum_${rowNumber}`).value = marksSum;
}
ثالثاً عملت دالة من خلالها بجمع كل الدرجات اللي تم قراءتها و بعدين بعرضها في مُربع نصي 👀
function checkInputMaxDegree(rowNumber) {
var validMaxDegreesCount = 0;
for (var i = 0; i < $("input[name='marks[]']").length; i++) {
if (parseInt($("input[name='marks[]']")[i].value) > parseInt(maxDegrees[i % maxDegrees.length])) {
$('#button_error').text(`the current value must be less than or equal ${maxDegrees[i % maxDegrees.length]}.`);
validMaxDegreesCount += 1;
} else {
validMaxDegreesCount -= 1;
}
}
if (validMaxDegreesCount * -1 >= $("input[name='marks[]']").length) {
getMarksSum(rowNumber);
}
}
رابعاً عملت دالة من خلالها بشيك علي الحد الأقصي لكل درجة ⬆
$('input[type=file]').change(function () {
const uploadedFile = $(this)[0].files[0];
if (uploadedFile.name.split('.').pop() == 'xlsx') {
var reader = new FileReader();
if (reader.readAsBinaryString) {
reader.onload = function (e) {
var workbook = XLSX.read(e.target.result, { type: 'binary' }), columnNotExists = false;
// Read the first sheet ONLY
var sheetRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[workbook.SheetNames[0]]);
// You can check the columns count in the sheet
if (Object.keys(sheetRows[0]).length != yourColumnsNames.length) {
console.log('please make sure that the columns count are equivalent.');
return false;
}
// You can check the columns name also
Object.keys(sheetRows[0]).forEach(function (key, index) {
if (yourColumnsNames[index] != key) {
console.log(`column ${yourColumnsNames[index]} not exists.`);
columnNotExists = true;
}
});
if (columnNotExists) {
return false;
}
$("tbody").html(null);
// Loop over each row and get the sum of each mark
sheetRows.map(function (row, index) {
$("tbody").append(setStudentMarksDataRow(index + 1, row));
getMarksSum(index + 1);
checkInputMaxDegree(index + 1);
});
};
reader.readAsBinaryString(uploadedFile);
}
} else {
console.log("file extension is invalid.");
}
});
و دي كانت آخر حاجة معانا و هي إني بقرأ الفايل المرفوع و بستخدم كل الدوال اللي فوق دي أثناء عملية القراءة 😎
و أخيراً لينك البروجكت 🚀
و بكدا أكون خلصت و أتمني تكون إستفدت ✔