Read . js file and write to page using javascript

Asked

Viewed 2,684 times

0

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

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

2 answers

1

Yes it is possible to read an Excel using Javascript, as long as you use the Javascript API File or the . xls(x) is on the same server as your page, so you would use Ajax to pick as string.

After reading with File or Ajax you can use this lib: https://github.com/SheetJS/js-xlsx

An example of use: http://faisalman.github.io/simple-excel-js/test/test.html, example of use:

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);

0

You can save your data to a file .js in JSON format, read it and display as you wish in the event window.onload. Follow a short 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])    
  }
}

  • Artur, thank you for the answer. However, I still have doubts: Is the first part of the code "Dados.js"? The second part I put in the HTML <Body> and it already reads the data?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.