How to read and write in excel file using nodejs? - node.js

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

Related

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 )
})

SheetJS How to create sheet from json and save it as buffer

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' })

convert JSON to Excel in node

I have a json response containing inner json content. I've added a library of json2xls and converted my json to excel. But, on the excel file in the address column, I'm getting [object object]. Is there any way where I could able to get those inner json value on excel?
var option = [{id: 1, name: "jason", address: [{city: "XYZ", state: "ABC"}]}]
var json2xls = require('json2xls');
var xls = json2xls(option);
fs.writeFileSync('data-report.xlsx', xls, 'binary');

How to add new rows into Tabulator table?

When I add new rows into Tabulator, I use some object with default values:
var defaults = { id: 11, country_id: 4 };
table.addRow( defaults );
table.addRow( defaults );
But Tabulator uses this object for data storage. Here all rows refer to the same data. Thus when one row is edited whole table is updated.
How to reproduce: open JS fiddle and edit country column
What is correct way to add rows into Tabulator?
The issue is because objects are passed by reference, if you want to pass the same object in to multiple rows you need to deep copy it to break the reference using the Object.assign function.
var defaults = { id: 11, country_id: 4 };
table.addRow(Object.assign({}, defaults));
table.addRow(Object.assign({}, defaults));
As workaround I do next:
var defaults = { id: 11, country_id: 4 };
var newRow = {};
for (var attr in defaults) {
newRow[attr] = defaults[attr];
}
table.addRow( newRow );
newRow = {};
for (var attr in defaults) {
newRow[attr] = defaults[attr];
}
table.addRow( newRow );
newRow = {};
for (var attr in defaults) {
newRow[attr] = defaults[attr];
}
table.addRow( newRow );

Resources