How can I update excel data using nodejs express - node.js

I have an excel sheet there are two columns one is the product name and the other is the product price and the price column is empty, to get the price I have to call API and then update the excel sheet with that price How can I achieve this?

You can use exceljs to work with excels. You can do something like this:
const Excel = require('exceljs');
const workbook = new Excel.Workbook();
workbook.xlsx.readFile('path to file')
.then(() => {
const worksheet = workbook.getWorksheet(1);
const row = worksheet.getRow(15);
row.getCell(1).value = 'pass_new_value';
row.commit();
return workbook.xlsx.writeFile('path-to-new-file');
}).catch((e) => {
console.log(e);
})
I would suggest you get all the data first and then write to the sheet instead of updating one column at a time.

Related

Update Spreadsheet with google API for continuous response using node js

I have registered a webhook which constantly generates the data. It has several fields, primary field is id. I am updating this data in a postgres table with update query. The problem is, I have a google sheet and the same data is there. After updating postgres table, I want to update the row in google sheet. How can I use googleSheetsInstance.spreadsheets.values.update() function to update the row with a specific id.
The code I wrote is like this:
let listOfLists = []
jsonArray.forEach(obj => {
const values = Object.values(obj);
listOfLists.push(values);
});
await googleSheetsInstance.spreadsheets.values.update({
auth,
spreadsheetId,
range: "'Sheet1'",
valueInputOption: "USER_ENTERED",
resource: {
majorDimension: "ROWS"
values: listOfLists,
},
});
I believe your goal is as follows.
You want to update rows of the Spreadsheet by searching ticket_id.
The sample value of listOfLists is [[1022, 'ab', 'cd', 'de'], [1023, 'xyz', 'hbw', 'pyg']].
From this sample value, in your situation, the value of ticket_id is column "A".
You want to achieve this using googleapis for Node.js.
You have already been able to get and put values for Google Spreadsheet with Sheets API.
In this case, how about the following sample script?
Sample script:
const googleSheetsInstance = // Please use your client.
const spreadsheetId = "###"; // Please set your Spreadsheet ID.
const sheetName = "Sheet1"; // This is from your script.
const listOfLists = [[1022, "ab", "cd", "de"], [1023, "xyz", "hbw", "pyg"]]; // This sample value is from your comment.
const obj = listOfLists.reduce((o, r) => ((o[r[0]] = r), o), {});
const {data: { values }} = await googleSheetsInstance.spreadsheets.values.get({auth, spreadsheetId, range: sheetName});
await googleSheetsInstance.spreadsheets.values.update({
auth,
spreadsheetId,
range: sheetName,
resource: {values: values.map((r) => obj[r[0]] || r)}, // or values.map((r) => obj[r[0]] || Array(r.length).fill(null)),
valueInputOption: "USER_ENTERED",
});
When this script is run, first, the values are retrieved from the sheet. And, the values of ticket_id of listOfLists are searched from column "A" of the retrieved values. And, the updated values are put on the sheet.
In this sample, 2 API calls are used.
Note:
If the values of ticket_id are not column "A", please modify const obj = listOfLists.reduce((o, r) => ((o[r[0]] = r), o), {}); and resource: {values: values.map((r) => obj[r[0]] || r)}, for your actual column.
References:
Method: spreadsheets.values.get
Method: spreadsheets.values.update

How to set columns name dynamically in Exceljs using Nodejs?

I am using Exceljs library to export data from the database using Nodejs, Now I am trying to set the column Header name dynamically from columns=36 (i.e. AK) to till the end or until it has data. but nothing helps.
column name strictly needs to start from 36th (i.e. AK) column name
labels array are like this -
[
'Type',
'Competition',
'IDB',
'SOV Focus',
'Medium',
'Tone'
]
So, I only need to print these in the header.
con.query(query, id, function (err, result) {
if (err) throw err;
const labels = [];
result.forEach((result) => {
labels.push(result.label);
});
labels.forEach((label, index) => {
const columnName = label;
// Get the column using the column index (in this case, 1)
const firstRow = worksheet.getRow(1);
// Set the value of the first cell in the row to the dynamic column name
firstRow.getCell(36, columnName);
});
});
But it is not working or throwing any errors.
Previously I used PHPSpreadhsheet in PHP but it was not able to handle huge data export and took much time to export data.
but in PHPspreadsheet it was so easy to set dynamic header names.
$sheet->setCellValueByColumnAndRow($col, 1, trim($labels[$k] , ','));
How will I set columns/header names dynamically?

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

How do I use the BigQueryDate class in the BigQuery nodejs client library?

I have a BigQuery table with a column of type "DATE". When I query the table with the nodejs client library as per below, the date elements in the data are objects of the BigQueryDate class. The documentation for the BigQueryDate class provides no explanation on how the use the class. I would like to convert the date objects to either JavaScript date objects, or date strings, so I can use the date data in my application.
const { BigQuery } = require("#google-cloud/bigquery");
const bigquery = new BigQuery();
const query = "SELECT * FROM `project.dataset.table`";
bigquery.query(query, function(err, rows) {
if (!err) {
console.log(rows);
}
});
The only parameter that the class has is value, which is the date as a string of the form yyyy-mm-dd.
const { BigQueryDate } = require("#google-cloud/bigquery");
const date = new BigQueryDate("2019-01-20");
date.value; // returns string "2019-01-20"
I encountered the same situation and found my answer as below:
I'm assuming that you've executed query and looping through the rows
// Import the Google Cloud client library
const {BigQuery} = require('#google-cloud/bigquery');
...
//connect to BigQuery and get the results
...
//loop through the rows and print it on console.
console.log('Rows:');
rows.forEach(
row => console.log(`${row.Col1}:${row.Col2}:${(row.DateCol3).value}:${row.col4}`)
);
Note: Here DateCol3 is date column in BigQuery dataset.
Hope this helps many others.

Get Saved Search values for multiple "formula" columns

Morning Gurus,
I have a saved search within Netsuite with multiple "formula" columns.
For example, there are several formulapercent' named columns, although thelabel' for each is unique.
However when using nlobjSearchResult.getValue('formulapercent') naturally I only get the first formulapercent column value.
How do I specify in getValue which of the formula columns I want to return the value for?
I really don't want to use a column number, in case I need to insert a new column to the saved search within Netsuite later.
Hoping for something along the lines of nlobjSearchResult.getValue('formulapercent','<label>')
I have tried the multi parameter option, but it does not work.
Simple fix?
Cheers
Steve
What I generally do is add a label to the saved search formula columns. Then:
var f1Val, f2Val, etc;
results.forEach(function(res){
var cols = res.getAllColumns();
cols.forEach(function(col){
switch(col.getLabel()){
case 'formula1' : f1Val = res.getValue(col); break;
case 'formula2' : f2Val = res.getValue(col); break;
...
}
});
});
Thought I'd add an answer I have since learned.
Instead of generically numbering the columns. For example:
var column = []
column[0] = new nlobjSearchColumn('formulanumeric').setFormula('myformula1');
column[1] = new nlobjSearchColumn('formulanumeric').setFormula('myformula2');
searchresults = nlapiSearchRecord(.......);
Instead of this, I found the easiest way to retrieve the formula column values was to uniquely define the columns:
var colformula1 = new nlobjSearchColumn('formulanumeric').setFormula('myformula1');
var colformula2 = new nlobjSearchColumn('formulanumeric').setFormula('myformula2');
var searchresults = nlapiSearchRecord('item',null,filters,[colformula1,colformula2]);
To then grab the formula results:
var formulares1 = searchresults[i].getValue(colformula1');
var formulares2 = searchresults[i].getValue(colformula2');
Removes the issue if column orders change.
Thought this might help somebody.
There is a method in the nlobjSearchResult object called getAllColumns(). Then I use the index of the formula columns to get the value.
I dont't know of any other way to get the values of the formula columns. Do note that if you use this method, if you change the order of the columns in the saved search it will break your script.
This works for me using SuiteScript 2.0. Place this into a function and pass in the needed variables
if(join){
if(summary){
if(String(name).startsWith("formula")){
return result.getValue(result.columns[column])
}else{
var searchResult = result.getValue({
name: name,
join: join,
summary:summary
});
return searchResult
}
}else{
if(String(name).startsWith("formula")){
return result.getValue(result.columns[column])
}else{
var searchResult = result.getValue({
name: name,
join: join
});
return searchResult
}
}
}else{
if(summary){
if(String(name).startsWith("formula")){
return result.getValue(result.columns[column])
}else{
var searchResult = result.getValue({
name: name,
summary: summary,
});
if((column==7 || column ==8 || column==10 || column==12) && type=='cases'){
return dropDown_Obj[column].getKeyByValue(searchResult)
}
return searchResult
}
}else{
if(String(name).startsWith("formula")){
return result.getValue(result.columns[column])
}else{
var searchResult = result.getValue({
name: name
});
return searchResult
}
}
}

Resources