I recently have been trying to convert some of my database to a google sheet, so users can submit things with a google form and it will automatically be put into a sheet, then I can pull the data using the npm package google-spreadsheet. But I want to be able to put that data in an array to use in my node.js application.
The below code basically simply gets the info off the document and displays it all upfront for me (at least the columns/rows I want)
function factdoc(fact) {
msg.channel.send(`Fact: ${fact.facts}`);
msg.channel.send(`------------------------`);
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('1QdEn0w02w-qcxHl5dLRn5Ld0IolbgFM9IV2TY2TPTSQ');
await promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[0];
const rows = await promisify(sheet.getRows)({
offset: 1
});
rows.forEach(row => {
factdoc(row);
})
}
if (msg.content == prefix + 'test') {
accessSpreadsheet();
msg.delete();
}
the output comes out like this
and the google sheet looks like this
So it's reading off the google sheet fine. However, after reading the documentation and watching a couple tutorials, I'm not sure how to take it further.
I want to take that information and store it an array so that if I were to type msg.channel.send(fact[0]);
for example, it would then display test0
. Or if I were to do a random fact, I could do something like this (obviously not exactly like this)
if (msg.content == prefix + "randomfact"){
randomfact = Math.floor(Math.random() * sheet.rowCount);
msg.channel.send(fact[randomfact]);
}
then it would count the rows, thus allowing me to put it into math.random
and allowing me to print a random fact off the list. I've been messing with this for a couple hours and keep breaking my code. I am not sure how to implement the functions from the documentation as I've never worked with this before.
I got it working, alls you need to do is remove the for each, create a new variable and parse the factdoc
function into the rows constent
function factdoc(fact) {
msg.channel.send(`Fact: ${fact.facts}`);
msg.channel.send(`------------------------`);
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('1QdEn0w02w-qcxHl5dLRn5Ld0IolbgFM9IV2TY2TPTSQ');
await promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[0];
const rows = await promisify(sheet.getRows)({
offset: 1
});
row = factdoc(rows[arrayno#]); //new code
}
if (msg.content == prefix + 'test') {
accessSpreadsheet();
msg.delete();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.