如何在Google Apps Script中向另一工作表的列表追加数据范围?
解决跨电子表格数据追加问题
你碰到的target range and source range must be on the same spreadsheet错误,核心原因是Range.copyTo()方法仅支持同一电子表格内的工作表间复制,跨独立电子表格时没法用这个方法。要实现跨表追加数据,得改成「读取源数据→写入目标表」的方式,下面是调整后的代码:
function archivesingle() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var ssd = SpreadsheetApp.openById('sheetid'); // 替换成你的目标表ID var idstoadd = ss.getActiveSheet(); var fulllist = ssd.getSheetByName("History"); Logger.log("Option#1 - Start") // step 1 - 获取目标表History的有效数据最后一行 var last_row = fulllist.getRange(1, 1, fulllist.getLastRow(), 1).getValues().filter(String).length; Logger.log("Step#1 - the last row on fulllist = "+last_row) // step 2 - 读取源数据范围的内容 var numheaderrows = 0; var sourcerange = idstoadd.getRange(1+numheaderrows, 14, idstoadd.getLastRow()-numheaderrows, 2); var sourceValues = sourcerange.getValues(); // 取出源数据的二维数组 Logger.log("Step#3 - the sourcerange = "+sourcerange.getA1Notation()); // step4 - 将数据写入目标表的下一行 if(sourceValues.length > 0){ // 避免空数据写入 fulllist.getRange(last_row+1, 1, sourceValues.length, sourceValues[0].length).setValues(sourceValues); Logger.log("Step#4 - 已将源数据追加到目标表"); } else { Logger.log("Step#4 - 源数据为空,无需写入"); } // step 6 - 提交所有待处理更改 SpreadsheetApp.flush(); Logger.log("Step#6 - Flushed the spreadsheet") Logger.log("Option#1 - Completed") return false; }
关键改动说明:
- 移除了原代码里的
sourcerange.copyTo(targetrange,{contentsOnly:true}),改用getValues()读取源数据,再用setValues()写入目标表 - 写入时需要指定完整的目标范围(行数、列数要和源数据匹配),所以用
sourceValues.length和sourceValues[0].length动态确定范围大小 - 增加了空数据判断,避免不必要的写入操作
注意:首次运行脚本时,需要授权让脚本获取目标电子表格的编辑权限。
内容的提问来源于stack exchange,提问作者Anthony Madle
相关产品推荐
相关产品推荐

