i want try multiload xls files and view values in SheetJS but work only last in array url.
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.7/xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = new Array();
url.push("2017_01_Zole.xls");
url.push("2017_03_TK.xls");
url.push("2017_05_Psy.xls");
for(var z = 0; z<url.length; z++){
var oReq = new XMLHttpRequest();
oReq.open("GET", url[z], true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {type:"binary"});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
// jsn = XLSX.utils.sheet_to_json(worksheet,{raw:true});
console.log(worksheet['F3'].v +' = '+ worksheet['J3'].v);
};
oReq.send();
}
</script>
</body>
</html>
After each loop I want to display the result in console.log. Unfortunately, it only shows me data from the last file.
Moved solution from question to answer:
EDIT:
Problem solved
var x = 0;
function xlsy(urls){
var oReq = new XMLHttpRequest();
oReq.open("GET", urls, true);
//.......
oReq.send();
x++;
if(x < url.length){
xlsy(url[x])
}
}
xlsy(url[0]);
Related
I have made 2 .js files with the scripts inside them which are then called by app.html
I'm trying to call both the spot price and 24hr rolling percentage change from Binance rest API. My problem is that it prints the percentage change in the spot pricing HTML element. I think it has something to do with the percentage symbol ID being the same as the spot price symbol ID but I'm not sure.
What did I do wrong?
Here are the finance rest API docs.
HTML
<div class="div-block-3">
<div class="text-block-2"><span class="currency-title">USD</span> <span class="currency-symbol">$</span><strong id="BTCUSDT" class="rates">11,794.00</strong></div>
<div id="BTCUSDT" class="text-block-6"><strong class="negative">-1.84%</strong></div>
</div>
24hr rolling percentage .js
function load() {
var url_base = "https://api.binance.com/api/v3/ticker/24hr?symbol="
var elements = document.getElementsByClassName('text-block-6');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].id;
var url = url_base + id;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url, true);
ourRequest.onload = function () {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
document.getElementById( obj.symbol ).innerHTML = obj.priceChangePercent;
};
ourRequest.send();
}
}
window.onload = load;
spot pricing .js
function load() {
var url_base = "https://api.binance.com/api/v3/ticker/price?symbol="
var elements = document.getElementsByClassName('rates');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].id;
var url = url_base + id;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url, true);
ourRequest.onload = function () {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
document.getElementById( obj.symbol ).innerHTML = obj.price;
};
ourRequest.send();
}
}
window.onload = load;
I am using the js-xlsx, here is a link to my excel sheet if needed. I'm using the following code:
/* set up XMLHttpRequest */
var url = "Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] =String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {type:"binary"});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet,{raw:true}));
}
oReq.send();
In the console loge I get an output of:
(3) […]0: Object { FirstName: "Mayuresh", MiddleName: "Dinkar ", LastName: "Joshi", … }1: Object { FirstName: "Arun", MiddleName: "Vikas", LastName: "Pathak", … }2: Object { FirstName: "Narendra", MiddleName: "Damodardas", LastName: "Modi", … }length: 3<prototype>: Array []
I'm sure not sure how to access that data. I don't know it's name to call it. I tried arr.length, but it only returned 1 and it should've returned 3. The JS files returns a length of 3, but I'm not sure where it's pulling that from. I just need some accessing that Array. Thanks
It looks like it's working. Try this to see...
let worksheet = workbook.Sheets[first_sheet_name];
let objects = XLSX.utils.sheet_to_json(worksheet,{raw:true});
let names = objects.map(object => `${object.FirstName} ${object.LastName}`);
console.log(names);
I am trying to use the XLSX library to read data from excelsheet but I am getting this:-
ERROR: _fs is undefined at xlsx.js (line 11388, col 59)
Here is my code :-
<html>
<head>
<title>Read Excel</title>
<meta meta http-equiv="Content-Type" content="text/html;" charset="UTF-8"/>
</head>
<body>
<script src="xlsx.js"></script>
<script>
function actionbegins(){
console.log("Inside the function action begins !!");
if(typeof XLSX === 'undefined' && typeof require !== 'undefined')
XLSX = require('xlsx');
var workbook = XLSX.readFile("Invoice.xlsx", {type: 'base64'});
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A2';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
console.log("we got the value as --> "+desired_value);
}
</script>
<button id="btnDoIt" onclick="actionbegins()" name="btnDoIt" class="btn btn-primary">do It !!</button>
</body>
</html>
I tried searching the net for a suitable answer but could not find any. Please suggest.
It was not working because the file wasn't loaded completely and it started processing it.
Here is the code that is working absolutely fine :
<html>
<head>
<title>Read Excel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script lang="javascript" src="dist/xlsx.core.min.js"></script>
</head>
<body>
<script>
function letsdoit(){
var url = "Invoice.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A1';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
alert("value is -- "+desired_value);
}
oReq.send();
}
</script>
<input type="file" name="file" id="selectfile" onchange="letsdoit()" />
</body>
</html>
I am parsing xlsx with js-xlxs .
var url = "test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {type:"binary"});
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) { /* iterate through sheets */
var worksheet = workbook.Sheets[y];
for (z in worksheet) {
/* all keys that do not begin with "!" correspond to cell addresses */
if(z[0] === '!') continue;
console.log(y + "!" + z + "=" + JSON.stringify(worksheet[z].v));
}
});
}
oReq.send();
which is working fine for me. i can traverse each single cell, but need to parse specific range with in xlsx like from row: A160-Q160 and column: 160-202
i read about range in documentation but not getting it , how to set the same with my example
I did it like below. Its working for me now
function handleFile(e) {
if(!window.FileReader) {
console.log("Browser doesn't support FileReader");
return;
}
var files = e.target.files, i, f,
rowRange = ["A"],//xls column array
/*setting range in xlsx, to parse and get with in range*/
lowerRangeRow = 160,//xls rows lower range
upperRangeRow = 202,//xls rows upper range
row1;
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {type: 'binary'});
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) { /* iterate through sheets */
var worksheet = workbook.Sheets[y];
for (z in worksheet){
/* all keys that do not begin with "!" correspond to cell addresses */
if(z[0] === '!') continue;
row1 = z.replace(/[^0-9]/g, '');
if(rowRange.indexOf(z.charAt(0)) > -1 && (row1>=lowerRangeRow && row1<=upperRangeRow)){
//console.log(worksheet[z].v.trim());
li = document.createElement("li");
li.appendChild(document.createTextNode(worksheet[z].v.trim()));
document.getElementById("xlsxDataList").appendChild(li);
}
}
});
};
reader.readAsBinaryString(f);
}
}
document.getElementById("file").addEventListener('change', handleFile, false);
I have tried to read excel file to follow the following tutorial.
http://code.psjinx.com/xlsx.js/
But I have failed to read excel file for undefine situation in the following highlighted line.... I have tried it in IE11.
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
obj.sheets = XLSXReader.utils.parseWorkbook(workbook, readCells, toJSON);
handler(obj);
}
**reader.readAsBinaryString(file)**;
The following answer describe, if you are going to load xlsx file from server. For uploading there is another code.
OPTION 1: This is a procedure, which works in Alasql library:
See files: 15utility.js and 84from.js for example
readBinaryFile(filename,true,function(a){
var workbook = X.read(data,{type:'binary'});
// do what you need with parsed xlsx
});
// Read Binary reading procedure
// path - path to the file
// asy - true - async / false - sync
var readBinaryFile = utils.loadBinaryFile = function(path, asy, success, error) {
if(typeof exports == 'object') {
// For Node.js
var fs = require('fs');
var data = fs.readFileSync(path);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
success(arr.join(""));
} else {
// For browser
var xhr = new XMLHttpRequest();
xhr.open("GET", path, asy); // Async
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var data = new Uint8Array(xhr.response);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
success(arr.join(""));
};
xhr.send();
};
};
OPTION 2: you can use Alasql library itself, which, probably, can be easier option.
alasql('SELECT * FROM XLSX("myfile.xlsx",{headers:true,sheetid:"Sheet2",range:"A1:D100"})',
[],function(data) {
console.log(res);
});
See the example here (simple Excel reading demo) or here (d3.js demo from Excel).