Reading Excel file using SheetJs - Javascript - javascript

I am trying to read Excel file using SheetJs
But getting following error.
Uncaught TypeError: Cannot read property '0' of undefined
Here is my file handler function
function handleFileSelect(evt) {
//Get the files from Upload control
var files = evt.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (evt) {
var data = evt.target.result;
var result;
/* convert from workbook to array of arrays */
var first_worksheet = data.Sheets[data.SheetNames[0]];
var data = XLSX.utils.sheet_to_json(first_worksheet, {header:1});
alert(result[0].Column1);
};
reader.readAsArrayBuffer(f);
}
}

You need to first read this data as an XLSX sheet first (Refer page 11)
workbook = XLSX.read(data, {type: 'binary'});
Followed by getting sheetnames from workbook (page 13)
var first_sheet_name = workbook.SheetNames[0];

Related

Angular convert multiple Files into base64 string

I try to convert multiple files into multiple base64 strings.
But somehow my reader only spits out the same file over and over again. Anyone an Idea how to fix it?
handleFileSelect(evt) {
var files = evt.target.files;
var file = files[0];
for (let item of files) {
this.postData.name = item.name;
this.postData.type = item.type;
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(item);
}
}
_handleReaderLoaded(readerEvt, item) {
var binaryString = readerEvt.target.result;
this.base64textString = btoa(binaryString);
this.postData.base64 = this.base64textString;
this.saveToDB();
this.image = "data:image;base64, ";
}

How to parse, and iterate through, all rows from an Excel sheet file using JavaScript

I am trying to parse and read every cell from an Excel sheet; it seems that I am parsing the file but I just can't go through each cell and display them.
I am using the following code:
var workbook = XLSX.read('datasets/persons.xlsx', { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
// console.log(sheet_name_list);
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
console.log(y);
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
console.log(roa);
if (roa.length > 0) {
result = roa;
}
});
I am getting an empty array when I try to print console.log(roa), any idea how I should iterate through each cell from the file?
you can use
XLSX.utils.sheet_to_row_object_array(workbook.Sheets[y])
to parse each cells in excel file.
Here is full code use to display Excel sheet file using JavaScript and JQuery.
function handleFile(e) {
//alert(e);
var exceljsonObj = [];
var files = e.target.files;
var i, f;
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 result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//var exceljsonObj = [];
var rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[y]);
exceljsonObj = rowObject;
for(var i=0;i<exceljsonObj.length;i++){
//var recordcount = exceljsonObj.length;
var data = exceljsonObj[i];
$('#myTable tbody:last-child').append("<tr><td>"+data.ID+"</td><td>"+data.Name+"</td><td>"+data.Months+"</td></tr>");
}
//alert(exceljsonObj.length);
$('#alermessage').each(function() {
//this points to item
alert('Record Count is '+exceljsonObj.length);
});
});
};
reader.readAsArrayBuffer(f);
}
}
$(document).ready(function(){
$('#files').change(handleFile);
});

Extract uploaded file using adm zip

I am trying to get the list of files in a uploaded file using adm-zip. As we cant get the path of the uploaded file , iam trying to convert the zip into a Buffer and pass it to the adm-zip. But zip.getEntries(); its not giving me the list of files.
checkZipFiles(){
var AdmZip = require("adm-zip");
var filesInput = document.querySelector('input[type="file"]').files[0];
var res;
var zip = new AdmZip(filesInput);
console.log(' zip is '+JSON.stringify(zip));
var zipEntries = zip.getEntries();
console.log(' zipEntries is '+zipEntries);
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.data.toString('utf8'));
}
});
var reader = new FileReader();
reader.readAsArrayBuffer(filesInput);
var bytes,buf ;
reader.onloadend = function(e){
var readLen=e.target.result.byteLength;
var arrayBuffer = reader.result
bytes = new Uint8Array(arrayBuffer);
console.log('insidebytes is '+bytes);
buf = new Buffer(e.target.result.byteLength);
for (var i = 0; i < buf.length; ++i) {
buf[i] = bytes[i];
}
console.log(e.target.result.byteLength+' length is '+bytes.byteLength);
var myZip = e.target.result;
console.log('bytes is '+bytes);
console.log('buf is '+buf);
zip = new AdmZip(buf);
// console.log(zip+' reader ');
var zipEntries = zip.getEntries();
console.log(' zip is '+zipEntries);
}
}
When i print the buffer it prints something like below , with the file name inside the zip.
121832 length is 121832
}+����Y���L�]��%:����_����ld� ��c{\��h7���L��e33�\"ԅտ׉��v�˕3�-��^�'�Ҁ霗�^�p�q�W��������vްR�����akny���Egr����G�%1/���Wer����\d���A�upR�L����up�jemF���� ��k9y��^Ն;h�1:ca delete.txt
�-�-F1p[
But AdmZip gives below error. Is the issue with the buffer or AdmZip not able to read the buffer?
Uncaught Invalid END header (bad signature) mainHeader.js?4281:35

XLSX parser for parsing excel

I am trying to parse xlsx file and save as a table (Along the lines of Excel to JSON javascript code? which is working fine for xls files). However, I am unable to convert to json and display as a table. Please find below the code snippet. Can anyone please guide how to close on this.
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLSX.read(data, {type: 'binary'});
var wb = XLSX.parse_xlscfb(cfb);
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
//var sCSV = XLSX.utils.make_csv(wb.Sheets[sheetName]);
var data = XLSX.utils.make_json(wb.Sheets[sheetName], {header:1});
alert(data.length);
//var columns = data[0].split(",");
$.each(data, function( indexR, valueR ) {
var sRow = "<tr>";
$.each(data[indexR], function( indexC, valueC ) {
sRow = sRow + "<td>" + valueC + "</td>";
});
sRow = sRow + "</tr>";
$("#my_file_output").append(sRow);
});
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
use this code :
note: use jszip.js and xlsx.js library
reader.onload = function(evt) {
debugger;
var data = evt.target.result;
//var xlsx = XLSX.read(data, {type: 'binary'});
var arr = String.fromCharCode.apply(null, new Uint8Array(data));
var xlsx = XLSX.read(btoa(arr), {
type: 'base64'
});
result = xlsx.Strings;
result = {};
xlsx.SheetNames.forEach(function(sheetName) {
var rObjArr = XLSX.utils.sheet_to_row_object_array(xlsx.Sheets[sheetName]);
if (rObjArr.length > 0) {
result[sheetName] = rObjArr;
}
});
return result;
// that.b64toBlob(xlsx, "binary");
};
reader.readAsArrayBuffer(file);
use readAsArrayBuffer method which will support on all browser.

Calling the contents within a list in JavaScript

So I have a website where the user puts a .csv file into a website and the website extracts it into a list in JavaScript. The full code that I am doing is to compare a .csv file that the user inputs into a website with the .csv file the website currently has. I want to be able to compare the two different files outside the function that I have below.
var a = [];
function compare(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csv = event.target.result;
var data = $.csv.toArrays(csv);
number = data.length;
for (i = 1; i < data.length; i++) {
a.push({date: data[i][0], url: data[i][5], count: data[i][6]});
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
var para = document.createElement("p");
var node = document.createTextNode(a[0].url);
para.appendChild(node);
var element = document.getElementById("demo");
element.appendChild(para);
At the end of this code snippet, I was testing to see if I can call upon the contents of the list a. However, I keep getting an "Uncaught TypeError: Cannot read property 'url' of undefined".
The error occurs at
var node = document.createTextNode(a[0].url);"
I think the problem is the async nature of the FileReader
function compare(file, callback) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
var a = [];
var csv = event.target.result;
var data = $.csv.toArrays(csv);
number = data.length;
for (i = 1; i < data.length; i++) {
a.push({
date: data[i][0],
url: data[i][5],
count: data[i][6]
});
callback(a);
};
}
//misplaced it in the onload handler
reader.onerror = function () {
alert('Unable to read ' + file.fileName);
};
}
then need to use the callback to access a
//here compare is an async method so to use the value of a after calling compare we will have to depend on a callback
compare(e.target.files[0], function (a) {
var para = document.createElement("p");
var node = document.createTextNode(a[0].url);
para.appendChild(node);
var element = document.getElementById("demo");
element.appendChild(para);
});
Demo: Fiddle

Categories

Resources