How can i get the data From FileReader() onload - javascript

I am converting excel data to json using XLSX and have to send the received data from onload to other functions. The conversion of excel to json is working just file.
var files = e.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = e => {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, { type: "array" });
let sheetName = workbook.SheetNames[0];
console.log(workbook);
let worksheet = workbook.Sheets[sheetName];
console.log("insde", XLSX.utils.sheet_to_json(worksheet));
console.log(XLSX.utils.sheet_to_json(worksheet))
};
reader.readAsArrayBuffer(f);
i just want to send XLSX.utils.sheet_to_json(worksheet) as data in other function
Thank your for your help :) .

You'd either pass back a callback or make this a Promisified function.
const fileToSheet = (file, callback) =>
var reader = new FileReader();
reader.onload = e => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: "array" });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
callback(XLSX.utils.sheet_to_json(worksheet));
}
reader.readAsArrayBuffer(file);
}
// elsewhere in your program
const files = e.target.files;
const f = files[0];
fileToSheet(file, console.log);
You can easily promisify this, and add error handling in the standard callback format that people usually use for a callback.

Related

How to parse pre-selected excel file into javascript object?

i know there are tonnes of solutions regarding this but no answers for pre-selected excel file.
var ExcelToJSON = function() {
this.parseExcel = function( file ) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.readAsBinaryString(file);
};
};
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
Here instead of browsing a file, i want to open the file '../img/file.xlsx' and convert it into an object. What is the best way to do it?
Did you try using xlsx?
install using
npm install xlsx
to read file,
const reader = require('xlsx')
const file = reader.readFile('../img/file.xlsx')

How can I read .xlsx row using javascript and convert it to .json file

I have some trouble on on converting my code to .json file.
document.getElementById('button').addEventListener("click", () => {
XLSX.utils.json_to_sheet(data, 'out.xlsx');
if(selectedFile){
let fileReader = new FileReader();
fileReader.readAsBinaryString(selectedFile);
fileReader.onload = (event)=>{
let data = event.target.result;
let workbook = XLSX.read(data,{type:"binary"});
console.log(workbook);
workbook.SheetNames.forEach(sheet => {
let rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheet]);
console.log(rowObject);
document.getElementById("jsondata").innerHTML = JSON.stringify(rowObject,undefined,4)
});
}
}
});
Also I need to read xlsx file per row and convert it as a .json file
Thanks for the help!

Date format changing when converting xlsx to json

I am trying to read data form xlsx file and converting it into json, but the date column value is changing
Here is the screenshot:Screenshot of my excel file from which i am reading data
Here is the code for reading data from excel file and converting into JSON:
onBasicUpload(event){
let workBook = null;
let jsonData = null;
const reader = new FileReader();
const file = event.files[0];
console.log(file,"file is here");
reader.onload = (event) => {
const data = reader.result;
workBook = xlsx.read(data, { type: 'binary' });
jsonData = workBook.SheetNames.reduce((initial, name) => {
const sheet = workBook.Sheets[name];
initial[name] = xlsx.utils.sheet_to_json(sheet);
console.log(jsonData,"jsonDAta");
return initial;
}, {});
const dataString = JSON.stringify(jsonData);
console.log(dataString,"stringify data");
this.jsonArr = JSON.parse(dataString)
console.log(this.jsonArr,"parsed json");
console.log(Object.keys(this.jsonArr['data'][0]))
}
reader.readAsBinaryString(file);
}
It is returning me this:
DOCDT is the value of the date being returned.
{"data":[{"DOCNO":"001","NETAMOUNT":30000,"IREF1":"50","IREF2":"100","DOCDT":43989},{"DOCNO":2,"NETAMOUNT":40000,"IREF1":40,"IREF2":90,"DOCDT":43989}]}
Try using this,
onBasicUpload(event){
let workBook = null;
let jsonData = null;
const reader = new FileReader();
const file = event.files[0];
console.log(file,"file is here");
reader.onload = (event) => {
const data = reader.result;
workBook = xlsx.read(data, { type: 'binary' , cellDates: true });
jsonData = workBook.SheetNames.reduce((initial, name) => {
const sheet = workBook.Sheets[name];
initial[name] = xlsx.utils.sheet_to_json(sheet);
console.log(jsonData,"jsonDAta");
return initial;
}, {});
const dataString = JSON.stringify(jsonData);
console.log(dataString,"stringify data");
this.jsonArr = JSON.parse(dataString)
console.log(this.jsonArr,"parsed json");
console.log(Object.keys(this.jsonArr['data'][0]))
}
reader.readAsBinaryString(file);
}
Dates are storred as a number within XLSX Files (See here or here). What you got is what is storred, so you got the number back.
According to the first reference, dates are storred as of January 1 1900. All you need to do now is have a function, that converts this number back to a date. Pure math.
Luckily, a quick SO search revealed, that this has been done before:
Converting Excel Date Serial Number to Date using Javascript

Reading local Excel file with js-xlsx using Angular 13?

I have my Angular-CLI frontend development server running locally on localhost:4200
I need to get a local Excel file stored on my PC, read its content and
make some calls to an API from the client side.
I'm trying to use js-xlsx, got it installed with npm install xlsx but I can't find how to get the file and read its content.
How can I import a local excel file with js-xlsx in Angular 13?
Here is working Example
onFileChange(ev) {
let workBook = null;
let jsonData = null;
const reader = new FileReader();
const file = ev.target.files[0];
reader.onload = (event) => {
const data = reader.result;
workBook = XLSX.read(data, { type: 'binary' });
jsonData = workBook.SheetNames.reduce((initial, name) => {
const sheet = workBook.Sheets[name];
initial[name] = XLSX.utils.sheet_to_json(sheet);
return initial;
}, {});
const dataString = JSON.stringify(jsonData);
document.getElementById('output').innerHTML = dataString.slice(0, 300).concat("...");
this.setDownload(dataString);
}
reader.readAsBinaryString(file);
}
In my case i want data like
[['1','2'],['3','4']]
also data like
{'1':'3', '2':'4'}
So that i did following code
uploadFile(uploadedFile){
let workBook = null;
const reader = new FileReader();
const file = uploadedFile[0];
reader.onload = (event) => {
const data = reader.result;
workBook = XLSX.read(data, { type: 'binary' });
const sheet_name_list = workBook.SheetNames;
this.xlData = XLSX.utils.sheet_to_json(workBook.Sheets[sheet_name_list[0]]);
log("xlData >>> ",JSON.stringify(this.xlData));
this.arraySaparater = (XLSX.utils.sheet_to_json(workBook.Sheets[sheet_name_list[0]], { header: 1 }));
this.arraySaparater = this.arraySaparater.filter((row)=>{
if(Array.isArray(row) && row.length){
return row;
}
else{
return false;
}
});
log('ArraySaparater >>>',JSON.stringify(this.arraySaparater));
}
reader.readAsBinaryString(file);
}

Read Simple JSON file (almost done)

I have a input and when I load it shows the file right in console.log.
But how do I get the actual json data from the file??
$('#importFlow').change(function () {
var files = event.target.files;
var file = files[0];
console.log(file);
console.log(JSON.parse(file)); //doesn't work
});
You'd need to use the FileReader API.
$('#importFlow').change(function () {
var files = event.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(event) {
var jsonObject = JSON.parse(event.target.result);
console.log(jsonObject); // Logs the parsed JSON
}
reader.readAsText(file);
});
You can read actual file content like this:
$('#importFlow').change(function () {
var files = event.target.files;
var reader, fileContent;
if (this.files)
{
reader = new FileReader();
reader.onload = function (e)
{
fileContent = e.target.result;
}
reader.readAsDataURL(this.files[0]);
}
});
In the above code, you can get the actual file data in the "fileContent" variable.

Categories