我将“ googleapis”库与Node.js结合使用,以将新行追加到Google电子表格中。这是我要附加的数据示例:
[ 9999, 1, 0, 0, 1, 0, '2019-09-19 14:16:10' ]
添加数据后,我看到Google电子表格设法以某种方式在日期值的开头添加了撇号。这一直发生,并且是一个问题,因为单元格值现在被认为是字符串而不是日期,并且我需要一个日期以便以后的查询按日期时间进行排序。这是单元格值结果:
'2019-09-19 14:16:10
这是我使用的脚本:
const { google } = require('googleapis');
const keys = require('../keys.json');
class GoogleSpreadsheet {
constructor() {
this.client = new google.auth.JWT(
keys.client_email,
null,
keys.private_key,
['https://www.googleapis.com/auth/spreadsheets']
);
}
insertRow(data, sheet, method) {
try {
this.client.authorize(async (error) => {
if (error) throw error;
const gsapi = google.sheets({ version: 'v4', auth: this.client });
if (method === 'append') {
const opts = this.buildAppendOptions(sheet, data);
await gsapi.spreadsheets.values.append(opts);
}
if (method === 'update') {
const opts = this.buildUpdateOptions(sheet, data);
await gsapi.spreadsheets.values.update(opts);
}
});
} catch (error) {
console.error('Could not insert raws into google spreadsheet')
}
}
buildAppendOptions(sheet, data) {
return {
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: sheet,
valueInputOption: 'RAW',
insertDataOption: 'INSERT_ROWS',
resource: {
values: data
}
}
}
buildUpdateOptions(sheet, data) {
return {
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: sheet,
valueInputOption: 'RAW',
resource: {
values: data
}
}
}
}
module.exports = GoogleSpreadsheet;
我这样称呼代码:
const date = new Date().toISOString().replace(/([^T]+)T([^\.]+).*/g, '$1 $2') // Gives format (yyyy-MM-dd HH:mm:ss)
const statistics = [[ 9999, 1, 0, 0, 1, 0, date ]];
const gs = new GoogleSpreadSheet();
gs.insertRow(statistics, process.env.GOOGLE_SPREADSHEET_NAME, 'append');
答案 0 :(得分:0)
答案是将valueInputOption更改为“ USER_ENTERED”:
buildAppendOptions(sheet, data) {
return {
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: sheet,
valueInputOption: 'USER_ENTERED',
insertDataOption: 'INSERT_ROWS',
resource: {
values: data
}
}
}