javascript - 如何获取一行并将该行和文本字符串合并为一个新行

标签 javascript google-apps-script google-sheets google-drive-api

我试图从一张工作表中获取一个范围,并添加该范围和一个字符串以在新工作表中创建一个新行。新工作表中的新行应该有字符串,然后是行。我虽然也许可以用数组来做到这一点,但它不起作用。

      //tradeName is the name of the source file. The code is super long so i did not include it in this snippet.      

      var fileList = DriveApp.getFilesByName(tradeName); 
      var fileId = fileList.next().getId();
      var sheetCurrent = SpreadsheetApp.getActiveSheet();
      var source = SpreadsheetApp.openById(fileId);
      var source_range = source.getRange("A20:AE20");

      sheetCurrent.appendRow([tradeName,A20:AE20]);

最佳答案

您不能混合范围和字符串值。 正如您所注意到的,appendRow 中的参数必须是一个数组,因此执行您想要的操作的正确方法是在添加新行之前将字符串添加到数组中。 另一方面,当您检索行值时,您会得到一个数组的数组(二维数组),因此我们必须仅采用内部数组并使用 unshift 方法在其他元素之前添加一个元素。

代码可能是这样的:

function myFunction() {
  var string = " ccccxxxx";
  var sheetCurrent = SpreadsheetApp.getActiveSheet();
  var source = SpreadsheetApp.openById(fileId);
  var source_range = source.getRange("A20:AE20");
  var source_rangeValue = source_range.getValues(); // 2D ARRAY   
  source_rangeValue[0].unshift(string);//add the string to the inner array
  sheetCurrent.appendRow(source_rangeValue[0]);
}

关于javascript - 如何获取一行并将该行和文本字符串合并为一个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267049/

相关文章:

javascript - 更新数组但保留 map 中的现有数组

javascript - 六边形 map 坐标 -> html 渲染

google-apps-script - 访问团队云端硬盘中的文件和文件夹

google-apps-script - 将单元格引用传递给电子表格函数

google-apps-script - Google Spreadsheet条件格式脚本

javascript - 使用脚本在 Google 表格中重新定位光标

Javascript正则表达式: Second occurrence of block: ABC. js音乐符号

javascript - Jest 测试无法解析 React 组件中的纯 HTML 标签

javascript - 谷歌电子表格的自定义 xml 解析函数

google-sheets - 有没有办法在电子表格的 'GoogleTranslate()' 函数中跳过翻译中的特定单词?