Read .js file and write to page using javascript

0

I have an Excel spreadsheet that I want to export some data to load into an HTML page. Searching the net I found that this is only possible if I have this data in a .JS file (data type .js).

So far so good. But how to read the data in the .js file and write them in my HTML page, without using PHP, preferably JavaScript? And there is something else, without having to click anything, you have to write automatically when you load the page.

    
asked by anonymous 28.09.2017 / 19:46

2 answers

1

If you can read an Excel using JavaScript, as long as you use the JavaScript File API or the .xls (x) is on the same server as your page, then you would use Ajax to get as a string.

After reading with File or with Ajax you can use this lib: link

An example usage: link , example usage:

Reading a file that is on the same server (host, port, and protocol) with Ajax:

var req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "arraybuffer";

req.onload = function(e) {
  var data = new Uint8Array(req.response);
  var workbook = XLSX.read(data, {type:"array"}); //Faz o "parse"
};
req.send();

With File API:

//A variavel file se refere ao elemento <input type="file">

var rABS = typeof FileReader !== 'undefined' && FileReader.prototype && FileReader.prototype.readAsBinaryString;

var reader = new FileReader();
var name = file.name; //Nome do arquivo vindo do input

reader.onload = function(e) {
    var data = e.target.result;
    var wb, arr;
    var readtype = {type: rABS ? 'binary' : 'base64' };
    if(!rABS) {
        arr = fixdata(data);
        data = btoa(arr);
    }
    function doit() {
        try {

            wb = XLSX.read(data, readtype); //Faz a leitura/parse

        } catch(e) { console.log(e); }
    }

    if(e.target.result.length > 1e6) opts.errors.large(e.target.result.length, function(e) { if(e) doit(); });
    else { doit(); }
};

if(rABS) reader.readAsBinaryString(file);
else reader.readAsArrayBuffer(file);
    
28.09.2017 / 20:15
0

You can save your data to a .js file in JSON format, read it and display it as you like in the window.onload event. Here is a small example:

var dados = {
  objeto1:{
    nome: 'teste',
    valor: 'batata'
  },
  objeto2:{
    nome: 'teste 2',
    valor: 'batata'
  }
}

window.onload = function () {
  for (var key in dados) {
    console.log(dados[key])    
  }
}
    
28.09.2017 / 19:59