【问题标题】:Google Apps Script - copy to existing spreadsheetGoogle Apps 脚本 - 复制到现有电子表格
【发布时间】:2017-12-14 07:01:38
【问题描述】:

我正在尝试使用 Google Apps 脚本 copy() 将我的主电子表格“发布”到输出电子表格,但每次都会获得多个副本,而不是替换输出文件。谁能建议一种方法来替换目标电子表格的内容,以便我可以为输出保留相同的文件 ID 并手动触发“发布”。尝试过copyTo,但只是制作了多张纸。

主电子表格是一个员工名册,需要多个经理在没有员工看到实时版本的情况下进行处理。经理完成更新后,可以推送给员工。

编辑:搞定了

function publishRoster() {
  var source = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = source.getActiveSheet();
  var updatedDateTime = sheet.getRange("A1");
  var now =  Utilities.formatDate(new Date(), "GMT+10:30", "dd/MM/yyyy H:mm")
 updatedDateTime.setValue("Last Published " + now);
  var sourceName = source.getSheetName();
//  var sValues = source.getDataRange().getValues();
  var destination = SpreadsheetApp.openById('my-destination-sheet-id-here');
  var destinationSheet = destination.getSheetByName(sourceName);
  if (destinationSheet == null ) { }
 else { destination.deleteSheet(destinationSheet); }
  sheet.copyTo(destination).setName(sourceName);
}

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    copyTo() 在目标电子表格中创建现有工作表的副本。 如果您想将特定工作表的更改发布到指定的目标工作表,那么您可以将数据从源工作表复制到目标工作表,而不是复制整个工作表。[这当然会在每次复制时创建新工作表]

    因此,将数据从主表复制/发布到从表的代码如下:

    var SOURCEID = 'xxxxxxxxxxxxx'; //put your source spreadsheet id here
        var SOURCESHEETNAME = 'XXXXX'; //put your source sheet name here
        var DESTINATIONID = 'xxxxxxxxxxxxx'; //put your destination spreadsheet id here
        var DESTINATIONSHEETNAME = 'XXXXX'; //put your destination sheet name here
    
        var data = SpreadsheetApp.openById(SOURCEID).getSheetByName(SOURCESHEETNAME).getDataRange().getValues();
        SpreadsheetApp.openById(DESTINATIONID).getSheetByName(DESTINATIONSHEETNAME).clear(); //This line is to clear the existing data in destination.
        SpreadsheetApp.openById(DESTINATIONID).getSheetByName(DESTINATIONSHEETNAME).getRange(1, 1, data.length; data[0].length).setValues(data);
        //data.length = no. of rows in source
        //data[0].length = no. of columns in source
        var now =  Utilities.formatDate(new Date(), "GMT+10:30", "dd/MM/yyyy H:mm");      
    SpreadsheetApp.openById(DESTINATIONID).getSheetByName(DESTINATIONSHEETNAME).getRange("A1").setValue("Last Published " + now);
    

    这不是经过测试的代码,如果出现任何问题,请告诉我,我很乐意为您提供帮助。 谢谢

    【讨论】:

    • 谢谢@Umair,我也需要它来复制格式和一些合并的单元格,所以 copyTo() 可能效果最好。我已经添加了一些行来删除和重命名新工作表,但现在我收到“TypeError: Cannot find function copyTo in object Spreadsheet”
    • 现在粘贴的代码有问题
    • 你想把时间戳放在单元格 A1 中吗?我已经更新了答案。抱歉回复晚了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多