对sheets.spreadsheets.values.append的API调用失败并出现错误:空响应

问题描述 投票:0回答:1

我正在使用 Google Sheet API 请求,但我什至没有收到错误消息来知道我缺少什么或我做错了什么。我越来越

API call to sheets.spreadsheets.values.append failed with error: Empty response

所以我尝试阅读文档这里。奇怪的是,当我的工作表中的数据大约少于 2500 行时,API 可以工作,但是当我将其增加到超过 2500 行时(请注意:我不知道此行为的确切行阈值,但它在 2000- 2500),API 调用不执行任何操作,并返回一个空响应。

setValues() 不是我的选择,因为 Google Sheets 的 API 请求更快并且更适合我的用例。

我的用例是我需要将公式从第一行复制并粘贴到最后一行。为了做到这一点,我循环为每一行创建一个新公式数组,然后将其存储在一个数组中(这使其成为一个二维数组),然后这就是我对 API 请求的输入值。

请参阅下面的代码片段:

  try{
    let lastRow = sheet.getLastRow();
    let formulaRow = headers + 1; 
    let formula = getNewFormulaRange(formulaRange, formulaRow);

    let sourceFormulaRange = sheet.getRange(formula);
    const sourceFormulas = sourceFormulaRange.getFormulas()[0]; // Extract just the first (and only) row of formulas

    let formulasToBeApplied = [];

    for (let i = formulaRow+1; i <= lastRow; i++) {
        // For each original formula, modify it to suit the new row number
        const adjustedFormulas = sourceFormulas.map(formula => 
            formula.replace(new RegExp(`(\\$?[A-Z]+)\\$?${formulaRow}`, 'g'), (match, cellReference) => {
                // Replace all instances of column references followed by 'formulaRow' with the same column reference followed by the new row number
                return `${cellReference}${i}`;
            })
        );
        formulasToBeApplied.push(adjustedFormulas);
    }

    const startingAppendRow = getNewFormulaRange( formulaRange, headers+2 );
    const valueRange = Sheets.newValueRange();
    valueRange.values = formulasToBeApplied;
    const options = {
      valueInputOption: "USER_ENTERED"
    }

    let result;
    if (formulasToBeApplied.length > 0) {
      result = Sheets.Spreadsheets.Values.append(valueRange, sheetId, `${sheet.getName()}!${startingAppendRow}`, options);
    }
google-apps-script google-sheets-api
1个回答
0
投票

不幸的是,从你的问题来看,我不知道你的实际情况。但是,根据我的经验,当 Sheets API 发生错误

Empty response
时,输入的值很大。 参考(作者:我) 如果这个情况和你的情况一样,下面的修改如何?

来自:

if (formulasToBeApplied.length > 0) {
  result = Sheets.Spreadsheets.Values.append(valueRange, sheetId, `${sheet.getName()}!${startingAppendRow}`, options);
}

致:

if (formulasToBeApplied.length > 0) {
  const split = 2000;
  const v = [...Array(Math.ceil(formulasToBeApplied.length / split))].map((_) => formulasToBeApplied.splice(0, split));
  result = v.map(values => Sheets.Spreadsheets.Values.append({ values }, sheetId, `${sheet.getName()}!${startingAppendRow}`, options));
}
  • 在此修改中,
    formulasToBeApplied
    的值通过拆分值附加到工作表中。
  • note that: I do not know the exact row threshold of this behavior but its between 2000-2500
    开始,行数为2000。但是,如果出现错误,请调整
    const split = 2000;
    的值并再次测试。
© www.soinside.com 2019 - 2024. All rights reserved.