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

后端 未结 7 656
慢半拍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条回答
  •  温柔的废话
    2020-12-01 17:59

    The selected answer does not work with the data containing Date cells. Actually it changes these cells to String and this is not expected behavior.

    I modified the code to check if the value is number and change only string values.

    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){
          if (typeof original_value != 'string') {
            return original_value;
          } else {
            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);
    }
    

    Have a nice day

提交回复
热议问题