Create JavaScript array from excel data using JavaScript and JSON - javascript

I'm trying to read and parse an excel file and create a JavaScript array object with the data.
The excel file will look like:
AA11 AA22 AN65
AB11 AB22 AN64
...
And I want the JavaScript array to look like:
[[AA11, AA22, AN65], [AB11, AB22, AN64],...]
So far I have the following code:
<input type="file" id="input" accept=".xls,.xlsx,.ods" />
<a id="result"></a>
<script type="text/javascript">
$("#input").on("change", function(e) {
var file = e.target.files[0];
if (!file) return;
var FR = new FileReader();
function byDocument(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, { type: "array" });
var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
var output = document.getElementById("result");
output.innerHTML = JSON.stringify(result, null, 2);
window.alert(result);
window.alert(result.type);
var array;
array = output.innerHTML;
output.parentNode.removeChild(output);
return array;
}
FR.onload = function(e) {
array = byDocument(e);
window.alert(array);
array.type = Array;
window.alert(array.type);
window.alert(array.length);
};
FR.readAsArrayBuffer(file);
});
</script>
This outputs text on the document that looks like an array, but when I try to store the data in a variable and index the array, it views the element array as some sort of string, or undefined. I'm wondering how to parse the excel file, or convert the JSON string, so that it behaves like a JavaScript array, which I could then index.

I believe it should be array = result instead of array = output.innerHTML. Or, at least, array = JSON.parse(ourput.innerHTML), because innerHTML is not an array, it's a string (you got it by JSON.strigify before).

It seems like you are already turning your result into JSON here:
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
According to the documents of xlsx this will convert your excel file into workable JSON. So result might be the value you need to return instead of array in your byDocument function.

The line output.innerHTML = JSON.stringify(result, null, 2); will turn the object into JSON and put it in the DOM.
const myJSObject = JSON.parse(myJSON) will return a JavaScript object and assign it to a variable.
I took a few of the DOM lines out of your function to make it less confusing, so you could try replacing your function with:
function byDocument(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, { type: "array" });
var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
var array;
array = result
return array;
}

Related

How to convert select2 array output to single string?

How to convert select2 array output to single string (separated by comma)? Just like this "task_owner":"Administrator,abc2". Current output is separated by comma but in single array "task_owner":["Administrator","abc2"]. This is because the DB is received by string, not array.
Another question, how to re-convert back to array since during editing, Ajax will send that String from DB and I maybe need to convert back to Array for display purpose.
I was referred to this Link but not working.
<form id="myForm">
<select type="text" class="form-control myClass" id="myID" multiple="multiple"></select>
</form>
$('.myClass').select2({
tags: true
});
$('#btnSubmit').on('click',function(){
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $('#myID').val();
if (owner.val() !== null && owner.val().length > 0){
var testOutput = $('#myID') = owner.val().join(',');
testOutput = Object.assign({}, {task_owner: testOutput.task_owner.join(",")})
}
// parameter that need to send to API
var obj = {
task_owner : testOutput,
// Another parameter...
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});
As dicussed:
$(".myClass").select2({
tags: true
});
$("#btnSubmit").on("click", function() {
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $("#myID").val(); //
if (Array.isArray(owner) && owner.length) {
testOutput = owner.join(",");
}
var obj = {
task_owner: testOutput
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});

Create structured JSON object from CSV file in JavaScript?

I want to create a JSON object from the contents of a CSV file. The CSV file is loaded locally via the FileReader API and that seems to work, however I am having trouble structuring the JSON in the desired way.
My code for loading the CSV file looks like this:
<!DOCTYPE html>
<html>
<body>
<p>Select local CSV File:</p>
<input id="csv" type="file">
<output id="out"> input file content</output>
<script>
var fileInput = document.getElementById("csv"),
readFile = function () {
var reader = new FileReader();
reader.onload = function () {
// Display CSV file contents
document.getElementById('out').innerHTML = reader.result;
};
reader.readAsBinaryString(fileInput.files[0]);
};
fileInput.addEventListener('change', readFile);
</script>
</body>>
</html>
The code above allows me to load the contents of the CSV file and display them on the current page. To structure the CSV data into the desired format above I tried the following, however it didn't work to me:
<!DOCTYPE html>
<html>
<body>
<script>
var fileReader = new FileReader();
function getFile(inputFile) {
let file = inputFile.files[0];
fileReader.readAsText(file);
}
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return JSON.stringify(result); //JSON
}
function readFile(evt) {
let parsed = csvJSON(evt.target.result);
return parsed;
}
</script>
</body>
</html>
How can I acquire my expected JSON object(s)? Any suggestions would be appreciated
One approach to this would be to iterate through your input CSV data on increments of "6" (where 6 represents the number of different bits of data for each student) to capture all student data per CSV row, and then populate an array of structured JSON objects in the desired format like so:
/* Helper function to perform the CSV to JSON transform */
function convertToJson(inputCsv) {
/* Split input string by `,` and clean up each item */
const arrayCsv = inputCsv.split(',').map(s => s.replace(/"/gi, '').trim())
const outputJson = [];
/* Iterate through input csv at increments of 6, to capture entire CSV row
per iteration */
for (let i = 6; i < arrayCsv.length; i += 6) {
/* Extract CSV data for current row, and assign to named variables */
const [date, firstName, middleName, lastName, uin, rsvpStatus] =
arrayCsv.slice(i, i + 6)
/* Populate structured JSON entry for this CSV row */
outputJson.push({
uin,
studentInfo: {
firstName,
middleName,
lastName,
rsvpStatus
}
});
}
return outputJson;
}
/* Input CSV data from your exsiting code */
const csv = `"Timestamp", "Enter First Name:", "Enter Middle Initial",
"Enter Last Name:", "Enter UIN:", "Are you attending the event?",
"2019/02/22 12:41:56 PM CST", "Jonathan", "Samson", "Rowe", "123456789",
"No", "2019/02/22 12:44:56 PM CST", "phil", "Aspilla", "beltran", "123456788",
"Yes"`
const json = convertToJson(csv);
console.log(json);
var csv = '"Timestamp","Enter First Name:","Enter Middle Initial","Enter Last Name:","Enter UIN:","Are you attending the event?"\n"2019/02/22 12:41:56 PM CST","Jonathan","Samson","Rowe","123456789","No"\n"2019/02/22 12:44:56 PM CST","phil","Aspilla","beltran","123456788","Yes"';
var csvJSON = function(csv) {
let vals = csv.split('\n'), ret = [];
for( let i = 1, len = vals.length; i < len; i++ ){
let person = vals[i].split(',');
ret.push({
uin : person[4],
studentInfo : {
firstName : person[1],
middleName : person[2],
lastName : person[3],
rsvpStatus : person[5]
}
});
}
return JSON.stringify(ret);
}
console.log(csvJSON(csv));
This is assuming the structure of the CSV is always the same.
If you are struggling to parse data, you can also use PapaParse, it has a lot of configurations and it's pretty easy to use:
// Parse CSV string
var data = Papa.parse(csv);
See more information at https://www.papaparse.com/demo

How to preserve json formate after saving it into local storage?

function receivedText(e) {
lines = e.target.result;
obj = JSON.parse(lines);
split();
}
function split() {
console.log(obj);
for (var i in obj) {
console.log(i);
if(i=="tagClassifications"){
console.log("tagClassifications IS MATCHED");
var c1=obj[i];
var ob2=JSON.stringify(c1);
console.log(ob2);
var obj1="{ \"tagClassifications\": "+ob2+" }";
console.log(obj1);
saveText(c1, "tagClassifications"+".json" );
}
if(i=="tagAssociations"){
console.log("tagAssociations IS MATCHED");
var c1=obj[i];
console.log(c1);
for(var j in c1){
console.log(c1[j]);
console.log("Length="+c1.length+"j:"+j);
var ob2=JSON.stringify(c1[j]);
var obj1="{ tagAssociations"+": ["+ob2+"]}";
console.log(obj1);
saveText(obj1, "tagAssociations"+j+".json" );
}
}
}
}
function saveText(text, filename){
var a = document.createElement('a');
a.setAttribute('href', 'data:application/json;charset=utf-8,'+encodeURIComponent(text));
a.setAttribute('download', filename);
a.click();
}
In Above javascript I am converting a json object into text file and saving it as a json formate. But saved json file having extension as .json, but format is as a plain text. plz tell me how to preserve json format.
In comments it was clarified that you were looking for ways to get the JSON string split over multiple lines, with indentation.
For that you can use the third argument of JSON.stringify. Also, it would be best to delay this conversion to JSON string until after you have constructed the whole object, so including the tagClassigifications or tagAssociations key name.
The part dealing with tagClassigifications would look like this:
var c1 = obj[i];
var obj2 = { tagClassifications: c1 }; // first build the object
var json = JSON.stringify(obj2, null, 2); // only then stringify
console.log(json);
You would do a similar thing for the tagAssociations.

Arrays and Localstorage

I'm having a little problem here, i have an array like this:
function crearObjetos()
{
var palabraPeso = "peso";
var palabraFecha = "Fecha";
var localStorageKey000 = "objetosPesoFecha";
var contador = 0;
var pesoFecha = new Array(); //THE ARRAY
while(contador < 365)
{
var nuevoObjeto = new Object;
var fechaActual = new Date();
nuevoObjeto.peso = 0;
nuevoObjeto.fecha = fechaActual;
nuevoObjeto.id = contador;
pesoFecha[contador] = nuevoObjeto; //SAVE OBJECTs IN THE ARRAY
contador = contador +1;
}
if (Modernizr.localstorage)
{
localStorage.setItem(localStorageKey000, pesoFecha); //STORAGE THE ARRAY
}
}
The problem is that, when i try to load the array in local storage, i can't acces any data, all are "undefined" and i don't know why... Here is how i load the data from the array (in this case only the first objetc):
function damePrimerObjetoPesoFecha()
{
//LOAD THE ARRAY FROM LOCAL STORAGE
var localStorageKey000 = "objetosPesoFecha";
var arrayDeObjetos = localStorage.getItem(localStorageKey000);
//CHECK IN AN ALERT IF THE DATA IS OK
alert("El primero que devuelve"+arrayDeObjetos[0].id);
//RETURN THE FIRSTONE
return arrayDeObjetos[0];
}
An array can't be pushed into localStorage just like how it is. You have to use JSON.stringify on it. This line :
localStorage.setItem(localStorageKey000, pesoFecha);
must be changed to
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha));
Similarly, when you're retrieving it from localStorage, you must use JSON.parse on it to convert it back to JSON. This line :
var arrayDeObjetos = localStorage.getItem(localStorageKey000);
must be :
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
Now when you access the first data, you wont get undefined.
Another alternative to this would be jStorage plugin which is wrapper around localStorage. It will take all the parsing problems from you and do it by itself if you pass an array or object to it.
Hope this helps!
localStorage only stores data as string.
You can strinify your array into JSON and save that and then parse it back when you load it
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha)); //STORAGE THE ARRAY
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
LocalStorage can store strings only. You also need to remember that JSON.stringify converts date objects to string, so when deserializing via JSON.parse you need to manually create date for each object from array based on that string.
Firstly:
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha));
and then
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
arrayDeObjetos.forEach(function(objecto){
objecto.fecha = new Date(objecto.fecha );
})
localstorage can only store strings.
If you want to store arrays & objects, you should convert them to JSON.
Here's a small helper:
var LS = {
set: function (key, val) {
return localStorage.setItem(key, JSON.stringify(val));
},
get: function (key) {
return JSON.parse( localStorage.getItem(key) );
}
};
Use it as follows:
// Store the array:
LS.set(localStorageKey000, pesoFecha);
// Retrieve the array:
var arrayDeObjetos = LS.get(localStorageKey000);
Here's the fiddle: http://jsfiddle.net/KkgXU/

copy contents of range object (Excel column) to an array via javascript

what I want to do is access an excel file, take the contents of a column and then store it in an array. I'm guessing this can be done by iterating through each element of the range object and copying it to an array. My current code is shown below:
function GetData(){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:\\Data.xls");
var excel_sheet = excel.Worksheets("Sheet2");
//returns a RANGE object
var myrow = excel_sheet.Columns(1);
//doing this puts a single range object in myarray
var myarray = new Array(myrow);
//try printing the contents of the range object
for (mycell in myrow){
document.getElementById('div1').innerHTML = mycell;
}
}
Please check the following code to get data from an excel file. Hope this helps you:
CODE:
function GetData(){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:\\Data.xls");
var excel_sheet = excel.Worksheets("Sheet2");
for(var i=2;i<20;i++){
var myrow = excel_sheet.Range("A"+i); //to read values in row A
document.getElementById('div1').innerHTML = myrow;
}
}
Tested in IE9.

Categories

Resources