SheetJS How to create sheet from json and save it as buffer - node.js

Documentations seems confusing to me. How can i create a document from a array of objects, each object representing a row and save it as buffer?

You can use the write function and pass the WritingOptions object to set the type of your workbook data.
Example:
const workbook = XLSX.utils.book_new()
const filename = 'mySheet'
const dataSheet = XLSX.utils.json_to_sheet(myJSONData)
XLSX.utils.book_append_sheet(workbook, dataSheet, filename.replace('/', ''))
and return for your controller, send it to the network, etc...
return XLSX.write(workbook, { type: 'buffer', bookType: 'csv' })

Related

How to read and write in excel file using nodejs?

I am using sheetjs for reading and writing purpose.
const data = {
'col1': 2,
'col2': 3,
'col3': ['1','2','3','4'],
'col4': {'test': '1'}
}
const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, `${tableName}`);
const file = XLSX.write(workbook, {
type: "buffer",
bookType: "xlsx",
bookSST: false
});
JSON and Array values are not getting added to file.
When I try to stringify JSON and array on reading the file, I am getting stringify value.
As my method is generic so JSON parse can't be done on columns individually.
Worksheet is getting created like this => t: 's", values: "{}"
Reading file like
const file = await this.s3Service.getFile(`${tableName}.xlsx`, uuid)
const workbook = XLSX.read(file.Body, {cellDates: true})
const sheet = workbook.Sheets[`${tableName}`]
let sheetData = XLSX.utils.sheet_to_json(sheet, {defval: null})
return sheetData
How can i store json and array as object

how to upload excel and find value in one schema and save object id in other schema

Suppose I have a upload button and that button can upload excel sheet, find the value one schema and save the value in other schema.
The code will take the company_name from excel and find the value from entity company_name and save the object Id in entity.
How it will happened if someone help?
{
entity: [{type: Schema.types.Object Id}]
}
{
entity: string,
company_name: string,
company_mobile: string,
}
You can use csvtojson package.
import csv from "csvtojson";
//parse request
parseRequestAndConvertCSVtoJSON = async (file) => {
//get actual file name from file array
let fileName = file.filename.replace(/\s/g, "");
//uploaded file path
let filePath = basedir + `/uploads/${fileName}`;
// Async / await usage
const jsonArray = await csv().fromFile(filePath);
//delete file from folder
fs.unlinkSync(filePath);
//redirect complete URL
return jsonArray;
};
And after this run a for of loop and store the data in loop
for(let element of data){ const object = {name: element.company_name}; let newCompany = new companyModel(object); company = await newCompany.save();}

How do i add Data from an array to object in React Native?

** The Following arrays have data that should be stored in data and labels which will then be shown in an app.**
const days[];
const level[];
for(var i=0;i<7;i++)
{
days.push((data2.Table[i].DayName).slice(0, 3))
level.push(data2.Table[i].Moisturevalue)
}
```const data = {
labels:["mon","Tue","Wed","Thu","mon","Tue"], //willing to update this from harcoded to dynamic
datasets: [
{
data: days, //Days Contains some numeric data that data should contain
}]```
So I assume that data2 is an object and that it has a prop Table that is an array. It appears that you want to extract the that you want to extract DayName (the first 3 characters) and MoistureValue from data2.Table. If this is true, here's how I would go about it:
const days = [];
const levels = [];
data2.Table.forEach(dataItem=>{
//using substring rather than slice makes it clear you are working with a string
days.push( dataItem.dayName.substring(0,3) )
levels.push( dataItem.Moisturevalue )
})

How to read images from excel sheet(have multiple worksheets) using nodejs?

I need to load .xlsx in node and angularjs app.
i have used some packages for that purpose like js-xlsx it give me a all the data, but I can't find images of the excel sheets nor in JSON neither in HTML generated by js-xlsx package.
var wb = XLSX.read(data.data, {
type: "array"
});
let sheets = [];
for (const key in wb.Sheets) {
sheets.push({
paneId: key.replace(/ /g, '').toLowerCase(),
title: key,
active: false,
disabled: false,
data: $scope.processData(XLSX.utils.sheet_to_csv(wb.Sheets[key]))
})
}
I have also tried.
XLSX.utils.sheet_to_json(wb.Sheets[key])
XLSX.utils.sheet_to_html(wb.Sheets[key])
$scope.processData is the function for converting csv to array.

Stringifying JSON data loses object I'm trying to stringify

I'm new to NodeJS and I'm trying to learn it a bit better by writing a Discord bot. But I'm having an issue with stringifying an object to JSON. I think it's having an issue with the array I'm setting, but I'm not sure how else I would do this. If I'm not supposed to set an array and using my guildMembers example below, how else should I insert this data into my JSON file?
I've looked through a few examples here on StackOverflow and found this particular article: JSON Stringify Removing Data From Object. However, it's not clear to me given what I'm trying to achieve.
var o = {};
var guildKey = guild.id;
o[guildKey] = [];
o[guildKey]['guildMembers'] = {};
var guildMembers = []
guild.members.forEach(function(guildMember, guildMemberId) {
if (!guildMember.user.bot){
var memberData = {
id: guildMember.id,
data: {
userName: guildMember.user.username,
nickName: guildMember.nickname,
displayName: guildMember.displayName,
joinedAt: guildMember.joinedAt
}
}
guildMembers.push(memberData);
};
});
o[guildKey]['guildMembers'] = guildMembers;
json = JSON.stringify(o);
I am expecting the data to show the guildMembers object with the array under the guildKey object. However, the JSON shows only the guildKey object with an empty array:
{"guildKey":[]}
You make guildKey an array and then try to use it as an object ...
Solution is:
o[guildKey] = {};
Just like in the mentioned post.
It is because you are assigning a key-value pair to an array with
o[guildKey]['guildMembers'] = { }; <= o[guildKey]
When iterating over an array to display the contents, JavaScript does not access non-integer keys. You should store o[guildKey] as an object instead.

Resources