我的网络应用程序后端采用 Node.js,用于从 Google Sheets 电子表格读取/写入。
我想使用一个查询来仅检索满足特定条件的行,但无法做到这一点。
以下方法接收单个(字符串)参数 customerID。 最终我想检索 cutomerID 列与提供的参数匹配且状态列等于 New
的单行(column2==customerID) && (column4=='新')
这是我到目前为止所拥有的:
async function getDraftOrderByID(customerID) {
try {
const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/ auth/spreadsheets.readonly'});
const sheets = google.sheets({version: 'v4', auth });
const spreadsheetId = 'MY-SPREADSHEET-ID';
const range = 'Orders!A3:D9';
const filter = 'column2 = "cid444"';
const myRetrievedData = await sheets.spreadsheets.values. get({
spreadsheetId,
range,
});
console.log('Retrieved from ORDERS tab: ', myRetrievedData.data.values);
} catch (error) {
console.error('Error retrieving draft Order ID :((( ', error);
throw error;
}
表格内容示例:
订单ID | 客户ID | 订购日期 | 状态 |
---|---|---|---|
X8G3F7 | cid222 | 2024 年 2 月 23 日 | 完成 |
V3B4R3 | cid444 | 2024 年 3 月 18 日 | 新 |
E5T2A2 | cid9999 | 2023 年 4 月 18 日 | 完成 |
Y5H5J6 | cid444 | 2023 年 12 月 27 日 | 进步 |
如果为 cid444 运行该方法,它应该检索第 2 行的内容,但当前运行此方法会导致返回 3、4、5 范围内的所有行: [ [“V3B4R3”、“cid444”、“2024 年 3 月 18 日”、“新”] [“E5T2A2”、“cid9999”、“2023 年 4 月 18 日”、“完成”] ['Y5H5J6','cid444','27DEC2023','进度'] ]
为了评估建议的解决方案,我将“filter”变量作为第三个参数添加到values.get, 还尝试使用“values.batchGetByDataFilter”并定义过滤条件 JSON。到目前为止还没有任何效果。
大多数情况下,错误看起来像: GaxiosError:收到无效的 JSON 有效负载。 未知名称“过滤器”:无法绑定查询参数。 在请求消息中找不到字段“过滤器”。
由于
myRetrievedData.data.values
已经返回 2D 数组,因此您可以使用 filter
来仅返回具有匹配 CustomerId 且状态为 New 的行
我能够通过替换得到你想要的结果:
console.log('Retrieved from ORDERS tab: ', myRetrievedData.data.values);
与:
console.log('Retrieved from ORDERS tab: ',
myRetrievedData.data.values.filter(
row => row[1] == customerID && row[3] == 'New'
));
参考: