How do I replace text in a spreadsheet with Google Apps Script?

后端 未结 7 671
慢半拍i
慢半拍i 2020-12-01 17:30

I wanna find a specified text in spreadsheet and replace it with other word. I tried like this.

sheet = SpreadsheetApp.getActiveSheet()
sheet.replaceText (\'         


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 18:14

    You can achieve this by reading in all values in the sheet (as an Array), Looping over the array, replacing the values, then writing the entire array back to the sheet.

    There is a basic example below. You may need to modify this if your sheet contains formulas, or if you want to replace the text more than once in a given cell.

    Note that any changes made to sheet between the time you read in and write out the data will be lost, and potentially could break this example.

    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);
    }
    

    Documentation:

    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()

提交回复
热议问题