【发布时间】:2019-11-10 08:11:30
【问题描述】:
我在 google 表中有以下数据,我尝试获取数组值 5 与昨天日期匹配的每一行 (N) 的更新。 (请注意,我必须将数据 csv 才能正确粘贴到此处,但它位于 Excel 工作表中,顶行已冻结)
运行前的数据
idRef|fName |lName|tourType|dateBooked|tourDate |Pax|phone |pickupAddress|Op|emailAddress |bookedSent|reminderSent|feedbackSent
1 |Josh |w |group |2019-02-12|2019-11-09|3 |821467371|test address |AS|test@mydomain.com|notSent |0 |0
12 |Jess |s |group |2019-02-22|2019-11-10|2 |1233333 |test address |as|test@mydomain.com|notSent |0 |0
2 |Nick |J |group |2019-02-11|2019-11-11|2 |821234124|test address |AS|test@mydomain.com|notSent |0 |0
3 |Mars |M |group |2019-02-08|2019-11-09|2 |821234124|test address |AS|test@mydomain.com|sent |0 |0
4 |Nicole |M |group |2019-02-07|2019-11-10|5 |54546456 |test address |AS|test@mydomain.com|sent |0 |0
5 |Tim |M |group |2019-02-08|2019-11-11|2 |821234124|test address |AS|test@mydomain.com|sent |0 |0
6 |Sue |h |group |2019-02-09|2019-11-09|3 |34534534 |test address |AS|test@mydomain.com|sent |0 |0
7 |carl |M |group |2019-02-10|2019-11-10|8 |54546456 |test address |AS|test@mydomain.com|sent |0 |0
8 |peter |M |private |2019-02-11|2019-11-11|2 |54546456 |test address |GC|test@mydomain.com|sent |0 |0
9 |jim |M |private |2019-02-12|2019-11-09|6 |54546456 |test address |GC|test@mydomain.com|notSent |0 |0
10 |bianca |M |private |2019-02-13|2019-11-10|3 |54546456 |test address |GC|test@mydomain.com|notSent |0 |0
11 |richman|M |private |2019-02-14|2019-11-11|2 |54546456 |test address |GC|test@mydomain.com|notSent |0 |0
代码
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const SCOPES = "https://www.googleapis.com/auth/drive";
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), listMajors);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error while trying to retrieve access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Prints the names and majors of students in a sample spreadsheet:
* @see https://docs.google.com/spreadsheets/d/xxxxxxxxxxx/edit
* @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
*/
function listMajors(auth) {
var today = new Date();
today = today.toISOString().slice(0, 10);
var dateYesterday = new Date();
dateYesterday.setDate(dateYesterday.getDate() - 1);
dateYesterday = dateYesterday.toISOString().slice(0, 10);
var dayYesterday = new Date();
var days = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
];
dayYesterday.setDate(dayYesterday.getDate() - 1);
dayYesterday = days[dayYesterday.getDay()];
var dateTomorrow = new Date();
dateTomorrow.setDate(dateTomorrow.getDate() + 1);
dateTomorrow = dateTomorrow.toISOString().slice(0, 10);
var dayTomorrow = new Date();
var futureDays = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
];
dayTomorrow.setDate(dayTomorrow.getDate() + 1);
dayTomorrow = futureDays[dayTomorrow.getDay()];
const sheets = google.sheets({ version: 'v4', auth });
sheets.spreadsheets.values.get({
spreadsheetId: 'xxxxxxxxxxx',
range: 'A2:N',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
var data = res.data.values;
var filteredRows = data.filter(eachRow);
function eachRow(eachRow) {
return (eachRow[13] === '0' || 'undefined') && eachRow[5] === dateYesterday; //2019-02-17
}
if (filteredRows != 0) {
for (x = 0; x < filteredRows.length; x++) {
console.log(filteredRows[x].join());
console.log(filteredRows[x][0]);
// let selectedRowIndex = filteredRows[x][0]+1 ;
let selectedRowIndex = rows.indexOf(filteredRows[x]);
console.log("Index: " + selectedRowIndex);
////////////////////UPDATING START////////////////////////////
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), updateCells);
});
/**
* Prints the names and majors of students in a sample spreadsheet:
* @see https://docs.google.com/spreadsheets/d/xxxxxx/edit
* @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
*/
function updateCells(auth) {
var sheets = google.sheets({ version: 'v4' });
authorize(function () {
var request = {
spreadsheetId: 'xxxxxxxxx', //
valueInputOption: 'RAW', // TODO: Update placeholder value.
resource: {
"data": [
{
"range": "N" + selectedRowIndex,
"majorDimension": "COLUMNS",
"values": [
[
1
],
]
}
]
},
auth,
};
console.log(selectedRowIndex);
sheets.spreadsheets.values.batchUpdate(request, function (err, response) {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(response, null, 2));
});
});
function authorize(callback) {
var auth = "https://www.googleapis.com/auth/drive";
if (auth == null) {
console.log('authentication failed');
return;
}
callback(auth);
}
}
////////////////////UPDATING END////////////////////////////
}
};
});
}
运行后的数据
idRef|fName |lName|tourType|dateBooked|tourDate |Pax|phone |pickupAddress|Op|emailAddress |bookedSent|reminderSent|feedbackSent
1 |Josh |w |group |2019-02-12|2019-11-09|3 |821467371|test address |AS|test@mydomain.com|notSent |0 |0
12 |Jess |s |group |2019-02-22|2019-11-10|2 |1233333 |test address |as|test@mydomain.com|notSent |0 |1
2 |Nick |J |group |2019-02-11|2019-11-11|2 |821234124|test address |AS|test@mydomain.com|notSent |0 |0
3 |Mars |M |group |2019-02-08|2019-11-09|2 |821234124|test address |AS|test@mydomain.com|sent |0 |0
4 |Nicole |M |group |2019-02-07|2019-11-10|5 |54546456 |test address |AS|test@mydomain.com|sent |0 |1
5 |Tim |M |group |2019-02-08|2019-11-11|2 |821234124|test address |AS|test@mydomain.com|sent |0 |0
6 |Sue |h |group |2019-02-09|2019-11-09|3 |34534534 |test address |AS|test@mydomain.com|sent |0 |0
7 |carl |M |group |2019-02-10|2019-11-10|8 |54546456 |test address |AS|test@mydomain.com|sent |0 |1
8 |peter |M |private |2019-02-11|2019-11-11|2 |54546456 |test address |GC|test@mydomain.com|sent |0 |0
9 |jim |M |private |2019-02-12|2019-11-09|6 |54546456 |test address |GC|test@mydomain.com|notSent |0 |0
10 |bianca |M |private |2019-02-13|2019-11-10|3 |54546456 |test address |GC|test@mydomain.com|notSent |0 |0
11 |richman|M |private |2019-02-14|2019-11-11|2 |54546456 |test address |GC|test@mydomain.com|notSent |0 |0
如您所见,代码更新了 col N 中的单元格,但没有在正确的索引处。 IE 上面应该将 col F = 2019-11-09(到昨天的相对日期)的每个 col N 更新为值 1,但它每次都会将正确的行跳过 1。
在 updateCells batchUpdate 函数中我调用"range": "N" + selectedRowIndex,
我可以在运行时更新多个单元格,但是 selectedRowIndex 与正确的行实际位置不匹配(val 5 = 昨天日期的所有行)。我通过使用函数调用从位于稍高一点的 for 循环范围之外无法访问变量,但也没有运气。我认为的问题似乎是第一行是冻结行。在我更高层的函数中,listMajors range: 'A2:N', 在没有标题单元格的情况下调用正确的数据,但是如何将此起点应用于我的第二个 batchUpdate 函数。还是我需要映射一个新数组或其他东西?有没有办法像 sheet.value.get 函数那样指定范围?
请问,selectedRowIndex 为什么不选择并更新正确的行?
【问题讨论】:
-
为了正确理解您的问题,您能否提供运行正确脚本前后的示例电子表格?通过这个,我想考虑这个问题。当然,请删除您的个人信息。
-
感谢@Tanaike 的回复,(请原谅电子表格中的 csv 文本,我无法粘贴带有数据的格式化表格)有两点需要澄清,请记住代码取决于第 5 列中的日期字段是昨天的日期,并且 col 0 中的 idRef 与我尝试正确使用的数组索引不同。然后回答您的问题,当我在上述数据上运行上述代码时(其中第 5 列是昨天的日期),它会更新我的第 1 行不正确的行。我已经编辑了问题以在运行前后添加更多信息和示例数据。谢谢!
-
感谢您的回复和补充信息。从您更新的问题和回复中,我可以确认值
12,Jess,s,group,2019-02-22,2019-11-10,2,1233333,test address,as,test@mydomain.com,notSent,0,1、4,Nicole,M,group,2019-02-07,2019-11-10,5,54546456,test address,AS,test@mydomain.com,sent,0,1、7,carl,M,group,2019-02-10,2019-11-10,8,54546456,test address,AS,test@mydomain.com,sent,0,1的最后一列已从0修改为1。 -
在这种情况下,当今天是
2019-11-11,当“F”列的值是昨天的2019-11-10时,最后一列被修改为1。我的理解正确吗? -
没错,田池。最后一列是 feedbackSent 应该更新为 1。
标签: javascript node.js for-loop google-sheets-api indexof