You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将发票数据写入Google Sheets工作表最后一行(避免覆盖)

解决方案

你的问题出在固定从第2行写入数据,导致覆盖原有内容。要实现追加到工作表最后一行,只需要修改写入数据的那行代码,结合getLastRow()获取当前已使用的最后一行,然后从下一行开始写入新数据。

修改步骤:

  • 获取invoicesSheet的最后一行行号:const lastRow = invoicesSheet.getLastRow();
  • 计算新数据的起始行:const startRow = lastRow + 1;
  • 增加非空判断,避免无发票数据时调用invoices[0].length报错

修改后的完整代码片段:

// Writes invoices data to the sheet.
if (invoices.length > 0) {
  const lastRow = invoicesSheet.getLastRow();
  const startRow = lastRow + 1;
  invoicesSheet.getRange(startRow, 1, invoices.length, invoices[0].length).setValues(invoices);
}

说明:

  • getLastRow()会返回工作表中包含数据的最后一行行号,如果工作表只有表头(第1行),它会返回1,此时startRow就是2,和你原来的逻辑一致,兼容空表的情况。
  • 增加invoices.length > 0的判断,防止当没有生成任何发票时,代码因invoices[0]不存在而抛出错误。

内容的提问来源于stack exchange,提问作者Chalet Adelheid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:03:35