我正在尝试使用 node.js googleapis v4 并使用 JWT 客户端授权来更新给定的电子表格单元格。
阅读效果很好,但我不明白如何写:
new Promise((resolve, reject) => {
sheets.spreadsheets.values.update({
auth: this._auth,
spreadsheetId: this._metaData.spreadSheetId,
range: range,
valueInputOption: 'USER_ENTERED'
},(err, resp) => {
if (err) {
console.log('Data Error :', err)
reject(err);
}
resolve(resp);
});
});
如何指定数据,以及如何将其传递给调用?
我知道我应该使用 ValueRange 对象,但是如何使用?
在更好地查看(糟糕的)文档后,我推断您必须在调用中传递请求对象:
return new Promise((resolve, reject) => {
sheets.spreadsheets.values.update(
{
auth: this._auth,
spreadsheetId: this._metaData.spreadSheetId,
range: "Sheet1!A1",
valueInputOption: "USER_ENTERED",
resource: { range: "Sheet1!A1", majorDimension: "ROWS", values: [["b"]] },
},
(err, resp) => {
if (err) {
console.log("Data Error :", err);
reject(err);
}
resolve(resp);
}
);
});
此代码用于更新电子表格单元格,查看编辑方法
import { JWT } from 'google-auth-library';
import { GoogleSpreadsheet } from 'google-spreadsheet';
const GOOGLE_DOCS_CLIENT_EMAIL = 'service account email';
const GOOGLE_DOCS_KEY = 'your key here';
const SPREADSHEET_ID = 'spreadsheet id';
const serviceAccountAuth = new JWT({
email: GOOGLE_DOCS_CLIENT_EMAIL,
key: GOOGLE_DOCS_KEY,
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
const doc = new GoogleSpreadsheet(
SPREADSHEET_ID,
serviceAccountAuth,
);
const getCellCoordinates = (cell: string) => {
const row = cell.charCodeAt(0);
const column = cell.substring(1);
return {
row: row - 65,
column: parseInt(column, 10) - 1,
};
};
const edit = async() => {
await doc.loadInfo();
const sheet = doc.sheetsByTitle['sheetName'];
await sheet.loadCells('A1:C1');
const {row, column} = getCellCoordinates('A1');
sheet.getCell(row, column).value = 'testing value';
await sheet.saveUpdatedCells();
}
(async () => {
await edit();
})();