1
I am trying to make a code that reads the data of an excel file and write them on the console. For this I am using the Sheetjs but I’m having a problem. Every time my code returns "Undefined" on my console, unless I put the console.log
within the onreadystatechange
, but in no way does this Arrow Function return me the data from the xlsx file. What am I missing?
var pega_dados_excel = () => {
var softwares_instalados;
var url = "test.xlsx"; // Inserir o nome do Arquivo excel(xls ou xlsx)
var req = new XMLHttpRequest(); // Inicia a requisição
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onreadystatechange = function(){
var data = new Uint8Array(req.response);
var workbook = XLSX.read(data, { type: "array" });
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
softwares_instalados = (XLSX.utils.sheet_to_json(worksheet));
}
req.send();
return softwares_instalados;
}
$(document).ready(function () {
console.log(pega_dados_excel());
});
EDIT1: After the change made, suggested by the Cardinal Cmte the island was as follows:
Thank you very much, I understood how you did and worked on my test, but is being returned 3
console.log
, being two voids and the last correctly, can you tell me why ? I will leave a print on the question– Samuel Machado
how’s your code? can I take a look.
– Cmte Cardeal
I updated the code on the question
– Samuel Machado
ah yes, the explanation is because of the
readyState
of the document, I believe. as it shows the documentation of Mozilla, "It returns "loading" while Document is loading, "Interactive" when it was loaded but its sub-resources (like images, for example) not yet, and "complete" when it was fully loaded." So there are 3 different stages, and therefore the 3console.log()
. If your question has been answered, return the code of your question to how it was initially and a vote if my answer was useful :D– Cmte Cardeal
It makes sense... I put an if inside the
onreadystatechange
to check if it is already OK and worked perfectly. the if stayed so:if (this.readyState == 4 && this.status == 200)
. Thank you so much for your help :)– Samuel Machado