如何使用Google Apps脚本替换电子表格中的文字?

Yur*_*uri 4 javascript google-sheets google-apps-script

我想在电子表格中找到指定的文本并将其替换为其他单词.我试过这样的.

sheet = SpreadsheetApp.getActiveSheet()
sheet.replaceText ('ga: sessions','Sessions');
Run Code Online (Sandbox Code Playgroud)

然后它说 "Cannot find function replaceText in object Sheet."

Cam*_*rts 6

您可以通过读取工作表中的所有值(作为数组),在数组上循环,替换值,然后将整个数组写回工作表来实现此目的.

下面有一个基本的例子.如果工作表包含公式,或者如果要在给定单元格中多次替换文本,则可能需要修改此项.

请注意,在您读入和写出数据之间对工作表所做的任何更改都将丢失,并且可能会破坏此示例.

function testReplaceInSheet(){
    var sheet = SpreadsheetApp.getActiveSheet()
    replaceInSheet(sheet,'ga: sessions','Sessions');
}

function replaceInSheet(sheet, to_replace, replace_with) {
  //get the current data range values as an array
  var values = sheet.getDataRange().getValues();

  //loop over the rows in the array
  for(var row in values){

    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value){
      return original_value.replace(to_replace,replace_with);
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }

  //write the updated values to the sheet
  sheet.getDataRange().setValues(values);
}
Run Code Online (Sandbox Code Playgroud)

文档:

Array.map:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

String.replace:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Sheet.getDataRange:https://developers.google.com/apps-script/reference/spreadsheet/sheet#getDataRange()

range.GetValues:https://developers.google.com/apps-script/reference/spreadsheet/range#getValues()


Ser*_*sas 6

来自Cameron Roberts的答案几乎在所有情况下都适用(如果所有单元格都只用字符串填充),并且只是为了键入方便(请接受他的答案),这里是相同的脚本,但map函数稍有变化:我添加了toString()返回参数。

function testReplaceInSheet(){
    var sheet = SpreadsheetApp.getActiveSheet()
    replaceInSheet(sheet,'values','test');
}

function replaceInSheet(sheet, to_replace, replace_with) {
  //get the current data range values as an array
  var values = sheet.getDataRange().getValues();

  //loop over the rows in the array
  for(var row in values){

    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value){
      return original_value.toString().replace(to_replace,replace_with);
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }

  //write the updated values to the sheet
  sheet.getDataRange().setValues(values);
}
Run Code Online (Sandbox Code Playgroud)