将列值复制到另一个 google 电子表格文件而不覆盖

Copy column value to another google spreadsheet file without overwriting

我有以下场景。 应按顺序复制公式电子表格中的某些列,而不要将旧内容覆盖到主电子表格文件中。

我设法组合了以下脚本

function copy() {

var ss = SpreadsheetApp.getActive(),
    target =ss.getSheetByName('Sheet2'),   //fill in the name of the sheet
    lastColumn = target.getLastColumn(),
    sourceVal = ss.getSheetByName('Sheet1').getRange("C1:C58")
        .getValues();
target.getRange(1, lastColumn + 1, sourceVal.length, sourceVal[0].length)
    .setValues(sourceVal);

var ss = SpreadsheetApp.getActive(),
    target =ss.getSheetByName('Sheet2'),   //fill in the name of the sheet
    lastColumn = target.getLastColumn(),
    sourceVal = ss.getSheetByName('Sheet1').getRange("H1:H58")
        .getValues();
target.getRange(1, lastColumn + 1, sourceVal.length, sourceVal[0].length)
    .setValues(sourceVal);
}

这将适用于所需数量的列,并且不会覆盖旧信息。

遗憾的是,我无法理解如何将其与其他电子表格文件一起使用。

最终结果应该从 10 个文件中读取,每个文件 2 列(列不连续)到最终的主文件中。

提前感谢您抽出宝贵时间。

这对我有用:

function copy() {
  var sources = [
    {id: '1XTdXQjcy48D63Yl-fHFOvCocZo5jWN10d_fYfhf5umo', // ID of first source file
     sheet1: 'Sheet1',
     range1: 'C1:C58',
     sheet2: 'Sheet1',
     range2: 'H1:H58'
    },
    {id: '12wpXOlkKI2Zb8n5op4xuWQrWn7fyiH8j49NV8kB2b9s',
     sheet1: 'Sheet1',
     range1: 'C1:C58',
     sheet2: 'Sheet1',
     range2: 'H1:H58'
    } // add next sheets
   ]
  sources.forEach(function(val) {
    val.val1 = SpreadsheetApp.openById(val.id).getSheetByName(val.sheet1).getRange(val.range1).getValues();
    val.val2 = SpreadsheetApp.openById(val.id).getSheetByName(val.sheet2).getRange(val.range2).getValues();
    return val
  })

  var target = SpreadsheetApp.getActive().getSheetByName('Sheet2')

  for (var i=0; i<sources.length; i++) {
    var lastColumn = target.getLastColumn()
    target.getRange(1, lastColumn + 1, sources[i].val1.length, sources[i].val1[0].length).setValues(sources[i].val1);

    var lastColumn = target.getLastColumn()
    target.getRange(1, lastColumn + 1, sources[i].val2.length, sources[i].val2[0].length).setValues(sources[i].val2);
  }
}

记得更改电子表格的 ID[1]、工作表名称和范围。

尝试使用 openById(id):

  • Opens the spreadsheet with the given ID.

代码示例:

 // The code below opens a spreadsheet using its ID and logs the name for it.
 // Note that the spreadsheet is NOT physically opened on the client side.
 // It is opened on the server only (for modification by the script).
 var ss = SpreadsheetApp.openById("abc1234567");
 Logger.log(ss.getName());

要访问不同的工作表并将其插入主文件,请使用 openById(id)

希望对您有所帮助。