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);
Related
I'm trying to retrieve a specific ID from the JSON file depending on user input and then display a picture based on the ID retrieved from the JSON file
function showCard() {
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj["data"][0]["id"]
document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
event.preventDefault();
}
I think what you need is below but I am not sure I understood your json structure:
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var oReq = new XMLHttpRequest();
oReq.open("GET", "https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper", true);
oReq.responseType = "json";
oReq.onload = function(e) {
JSONObject json = new JSONObject(res);
JSONArray ja = json.getJSONArray("data");
JSONObject obj = ja.getJSONObject(0);
var imgId = obj.id;
document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
}
oReq.send();
I tried to answer your problem after identifying your problem.
function showCard()
{
event.preventDefault();
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj[0].id
document.getElementById("chosenCard").src =
"https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jpg";
}
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]);
I am trying to upload multiple images. So I read that I can generate a temporary url and send them with ajax.
The idea is push the url created with filereader into an array and the send with ajax but the url's are not pushed properly. When I see the result I got like an empty array:
But if I click the arrow I can see the url's inside
But them seems Inaccessible.
This is my code:
$('form').on('submit',function(e) {
e.preventDefault();
var filesToUpload = document.getElementById("myFile");
var files = filesToUpload.files;
var fd = new FormData();
var arr = [];
if (FileReader && files && files.length) {
for (i=0; i< files.length; i++){
(function(file) {
var name = file.name;
var fr = new FileReader();
fr.onload = function () {
arr.push(fr.result);
}
fr.readAsDataURL(file);
})(files[i]);
}
console.log(arr);
}
});
The final idea is convert to string JSON.stringify(arr) and then parse in php json_decode($_POST['arr']).
Of course this is not working because JSON.stringify(arr) gets empty.
Maybe the following simple solution works for you? I placed your console.log() and your ajax call into the fr.onload() method but fire it only, after your results array has been filled up with all values:
$('form').on('submit',function(e) {
e.preventDefault();
var filesToUpload = document.getElementById("myFile");
var files = filesToUpload.files;
var fd = new FormData();
var arr = [];
if (FileReader && files && files.length) {
for (var i=0; i< files.length; i++){
(function(file) {
var name = file.name;
var fr = new FileReader();
fr.onload = function () {
arr.push(fr.result);
if(arr.length==files.length) {
console.log(arr);
// place your ajax call here!
}
}
fr.readAsDataURL(file);
})(files[i]);
}
}
});
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).