cant write on my EXCEL file using Javascript

39 views Asked by At

i have been trying to write on a constant (fixed path) excel file where i want to add a new row every time the save button is clicked but feeling lost and have no clue how to get it done

my JS code

document.getElementById('save').addEventListener('click', async function saveStudent() {
    // Note: You don't need to use require for XLSX in a browser environment
    // Include SheetJS library in your HTML file using a script tag
    // <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

    // You can directly use the global XLSX object
    const XLSX = window.XLSX;

    const workbook = XLSX.readFile("students.xlsx");
    const worksheet = workbook.Sheets["Sheet1"];

    // Retrieve values from the form
    var fullname = document.getElementById('fullname').value.trim();
    var grade = document.getElementById('grade').value.trim();
    var birthdate = document.getElementById('birthdate').value.trim();
    var address = document.getElementById('address').value.trim();
    var phonenumber = document.getElementById('phonenumber').value.trim();

    // Check if any field is empty
    if (!fullname || !grade || !birthdate || !address || !phonenumber) {
        alert('Please fill in all information.');
        return;
    }

    // Add data to the worksheet
    worksheet.addRow({ fullname: fullname, grade: grade, birthdate: new Date(birthdate), address: address, phonenumber: phonenumber });

    console.log('added');

    // Write the workbook back to the file (save changes)
    XLSX.writeFile(workbook, "students.xlsx");

    // Clear the form inputs
    clearInputs();
});

// Your clearInputs function remains the same
function clearInputs() {
    // Clear all input fields
    document.getElementById('fullname').value = '';
    document.getElementById('grade').value = '';
    document.getElementById('birthdate').value = '';
    document.getElementById('address').value = '';
    document.getElementById('phonenumber').value = '';
}

an error that keeps coming up is :

xlsx.full.min.js:12  Uncaught (in promise) Error: Cannot access file students.xlsx
    at j (xlsx.full.min.js:12:15462)
    at Wg (xlsx.full.min.js:23:13327)
    at Object.Vg (xlsx.full.min.js:23:14506)
    at HTMLButtonElement.saveStudent (addstudentscript.js:9:27)  

and whenever i try to import-> require("xlsx"); it gives the following error

addstudentscript.js:2  Uncaught (in promise) ReferenceError: require is not defined
    at HTMLButtonElement.saveStudent (addstudentscript.js:2:18)

i tried a lot of tutorials but i cant figure out on how to write or edit the original sheet with no new copies

0

There are 0 answers