如何将发票数据写入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
相关产品推荐
相关产品推荐

