Read, modify a cell in an Excel file

Hi, I’m trying to load the SheetJS library to read and modify cells in an excel file and save it.
The problem:
I keep getting the following error: the XLSX.read function is missing or inaccessible.

I’ve tried loading the library with an API but it does the same thing.
Currently I’m opening a window to select the library and then the .xlsx file because I’ve had path problems, it couldn’t find the files.

Thanks for your help.

runtimeScene.setBackgroundColor(100, 100, 240);

let isSheetJSLoaded = false; // Variable pour vérifier si SheetJS est chargé

// Ajouter un bouton pour sélectionner un fichier bibliothèque
function ajouterBoutonBibliothèque() {
    const boutonBibliothèque = document.createElement("button");
    boutonBibliothèque.textContent = "Charger la bibliothèque";
    boutonBibliothèque.style.position = "absolute";
    boutonBibliothèque.style.top = "20px";
    boutonBibliothèque.style.left = "20px";
    boutonBibliothèque.style.padding = "10px 20px";
    boutonBibliothèque.style.backgroundColor = "#4CAF50";
    boutonBibliothèque.style.color = "white";
    boutonBibliothèque.style.border = "none";
    boutonBibliothèque.style.cursor = "pointer";

    boutonBibliothèque.onclick = () => {
        ouvrirBoiteDialogueBibliothèque();
    };

    document.body.appendChild(boutonBibliothèque);
}

// Ouvrir une boîte de dialogue pour sélectionner le fichier bibliothèque
function ouvrirBoiteDialogueBibliothèque() {
    console.log("Ouverture de la boîte de dialogue pour sélectionner une bibliothèque...");
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".js"; // Accepter uniquement les fichiers JavaScript
    input.style.display = "none";

    input.onchange = (event) => {
        const file = event.target.files[0];
        if (!file) {
            console.error("Aucun fichier bibliothèque sélectionné.");
            return;
        }

        console.log("Bibliothèque sélectionnée :", file.name);

        const reader = new FileReader();
        reader.onload = (e) => {
            console.log("Contenu de la bibliothèque chargée :", e.target.result.slice(0, 200)); // Affiche les 200 premiers caractères
            const script = document.createElement("script");
            script.textContent = e.target.result; // Charger le contenu du fichier dans un <script>
            document.head.appendChild(script);
            console.log("Vérification détaillée de SheetJS :", window.XLSX);
            if (!window.XLSX) {
                console.error("SheetJS n'est pas chargé correctement dans window.XLSX !");
                return;
            }
            if (typeof window.XLSX.read !== "function") {
                console.error("La fonction XLSX.read est absente ou inaccessible.");
                console.log("Liste des clés dans window.XLSX :", Object.keys(window.XLSX));
            }

            console.log("Bibliothèque SheetJS chargée depuis :", file.name);
            isSheetJSLoaded = true; // Met à jour l'état pour indiquer que SheetJS est chargé
            ajouterBoutonFichier(); // Activer le bouton pour sélectionner le fichier Excel
        };
        reader.readAsText(file);
    };

    document.body.appendChild(input);
    input.click();
}


// Ajouter un bouton pour sélectionner un fichier Excel
function ajouterBoutonFichier() {
    const boutonFichier = document.createElement("button");
    boutonFichier.textContent = "Sélectionner un fichier Excel";
    boutonFichier.style.position = "absolute";
    boutonFichier.style.top = "60px";
    boutonFichier.style.left = "20px";
    boutonFichier.style.padding = "10px 20px";
    boutonFichier.style.backgroundColor = "#2196F3";
    boutonFichier.style.color = "white";
    boutonFichier.style.border = "none";
    boutonFichier.style.cursor = "pointer";

    boutonFichier.onclick = () => {
        if (!isSheetJSLoaded) {
            console.error("SheetJS n'est pas chargé. Veuillez charger la bibliothèque d'abord.");
            return;
        }
        ouvrirBoiteDialogueFichier();
    };

    document.body.appendChild(boutonFichier);
}

// Ouvrir une boîte de dialogue pour sélectionner un fichier Excel
function ouvrirBoiteDialogueFichier() {
    console.log("Ouverture de la boîte de dialogue pour sélectionner un fichier Excel...");
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".xlsx, .ods"; // Accepter uniquement les fichiers Excel ou ODS
    input.style.display = "none";

    input.onchange = (event) => {
        const file = event.target.files[0];
        if (!file) {
            console.error("Aucun fichier Excel sélectionné.");
            return;
        }

        console.log("Fichier sélectionné :", file.name);

        const reader = new FileReader();
        reader.onload = (e) => {
            const fileBuffer = new Uint8Array(e.target.result);
            manipulerFichier(fileBuffer, file.name);
        };
        reader.readAsArrayBuffer(file);
    };

    document.body.appendChild(input);
    input.click();
}

// Manipuler un fichier Excel après sélection
function manipulerFichier(fileBuffer, fileName) {
    const XLSX = window.XLSX || XLSX;
    if (!XLSX || typeof XLSX.read !== "function") {
        console.error("SheetJS n'est pas correctement chargé ou la fonction XLSX.read est manquante !");
        return;
    }

    console.log("Contenu de XLSX :", XLSX);

    try {
        const workbook = XLSX.read(fileBuffer, { type: "array" });

        const sheetName = workbook.SheetNames[0];
        const sheet = workbook.Sheets[sheetName];

        console.log("Feuille chargée :", sheetName);
        console.log("Valeur actuelle de A1 :", sheet["A1"] ? sheet["A1"].v : "Vide");

        sheet["A1"] = { v: "Nouvelle Valeur" };
        console.log("Cellule A1 modifiée :", sheet["A1"].v);

        const newFileBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });

        sauvegarderFichier(newFileBuffer, "modifié_" + fileName);
    } catch (error) {
        console.error("Erreur lors de la manipulation du fichier :", error);
    }
}

// Sauvegarder un fichier Excel modifié
function sauvegarderFichier(fileBuffer, fileName) {
    const blob = new Blob([fileBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();

    console.log("Fichier sauvegardé :", fileName);
}

// Initialiser l'interface utilisateur
ajouterBoutonBibliothèque();