How to set columns name dynamically in Exceljs using Nodejs? - node.js

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?

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 can I update excel data using nodejs express

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.

Nodejs find array property value based on value of another property

I am having trouble finding the value of a property in an array based on the value of another property. I am trying to assign the variable x with the value of sensors.type when searching for a specific sensorID. For example in the table below if I have the value of the sensor ID (yellow box) I am trying to assign the value of the type (red box) to the variable x.
I load an array 'sensors' with data from a PostgreSQL database with the following code:
var sensors = [];
var pgp = require('pg-promise')(options);
var connection = "postgres://xxxxxxx:yyyyyyy#xxx.xxx.xxx.xxx/heatmap"
var db = pgp(connection);
getSensors();
setInterval(getSensors,10000)
function getSensors(){
var q = "select * from sensors order by id"
db.query(q)
.then(function (data) {
data.forEach((s)=>{
sensors[s.mac.trim()] = s
console.log(s)
})
}, function (reason) {
console.log(reason);
})
.catch(function (error) {
console.err("Query error, "+error);
});
}
when I run the command console.table(sensors) this is what I see ..
Also I can see details for each record with console.dir(sensors) ...
I have an input string which I parse to get the sensorId I want to search the array for and can verify it exists with a valid value via console.log output.
var sensorId = rawData.substring(6,18);
var sensorRecord = sensors[sensorId];
I cannot seem to find a way of searching the array for the sensorType and assigning the value of the associated 'type' from the array to a variable.
I thought the following would:
var sensorType = sensors[sensorId].type;
But it returns the following error:
Would appreciate any help and guidance.

SQLite - Update field if new value isn't empty

I'm making a little web interface with nodejs, express and sqlite3. There's a table with a fixed number of rows and columns, which can be updated through a form. The user isn't required to fill out all of the fields, so there's a lot of empty values in the post request. I only want to write back the the populated fields to the database and ignore the empty ones. I can think of a number of ugly and tedious ways to achieve this, but I'm sure there's some really simple solution I don't know of.
app.post('/updatevals', (req, res) => {
for (const m in req.body) {
const val = req.body[m]; // val = ['value1', '', '', 5]
// user left index 1 + 2 empty
// last value is primary key
// Overwrites val2 + val3 with empty strings...
const sql = "UPDATE mytable SET val1=?, val2=?, val3=? WHERE id=?";
db.run(sql, val, (err) => {});
}
});

Excel to JSON conversion using Node JS

I have been trying to convert excel sheet data to json format and I have already various modules like "xls-to-json","xls-to-json-lc","node-excel-to-json", So far I have got empty response.
My sample code goes like this :
var node_xj = require("xls-to-json");
node_xj({
input: req.file.path, // input xls
output: "output.json", // output json
sheet: "a" // specific sheetname
}, function(err, result) {
if(err) {
console.error(err);
} else {
console.log("--------result----");
console.log(result);
}
});
My excel sheet contains very simple data :
What am i doing wrong in this , I am getting file and its valid path .
got the solution , all the libraries consider first row as header , so it was not getting displayed , it got displayed when i added 2nd row and every module has got its own structure of output/ response. some modules consider excel headers in output and skip the first row and few include first row .

Resources