繁体   English   中英

在 Google 表格中使用 Google Apps 脚本时如何防止日期变成字符串?

[英]How to keep the date from turning into a String when using a Google Apps Script in Google Sheets?

我使用在大型 Google 电子表格中发布的脚本,将字符串替换为数字。

它很好用,但问题是,日期变成了 String

我认为问题出在toString()方法上,但我找不到任何替代方法来使代码正常工作。

=> 有没有人有办法避免这个问题?

脚本

 function runReplaceInSheet(){ var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3"); // get the current data range values as an array // Fewer calls to access the sheet -> lower overhead var values = sheet.getDataRange().getValues(); // Replace replaceInSheet(values, 'datateam', '42007860'); // Write all updated values to the sheet, at once sheet.getDataRange().setValues(values); } function replaceInSheet(values, to_replace, replace_with) { //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; } }

在此处输入图像描述

在此处输入图像描述

  • 您想要替换电子表格的值。
    • 在您的脚本中,您希望将42007860 datateam
  • 您想使用 Google Apps 脚本实现此目的。

如果我的理解是正确的,这个答案怎么样? 请认为这只是几个答案之一。

模式一:

在此模式中,使用getDisplayValues()代替getValues()

修改后的脚本

请按如下方式修改您的脚本。 本次修改,修改了runReplaceInSheet()的function。

function runReplaceInSheet(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3");
  //  get the current data range values as an array
  //  Fewer calls to access the sheet -> lower overhead 
  var values = sheet.getDataRange().getDisplayValues(); // Modified

  // Replace  
  replaceInSheet(values, 'datateam', '42007860');


  // Write all updated values to the sheet, at once
  sheet.getDataRange().setValues(values);
}

模式二:

在此模式中,使用 TextFinder 代替replaceInSheet()setValues()

修改后的脚本

请按如下方式修改您的脚本。 本次修改,修改了runReplaceInSheet()的function。 而且,在此修改中,没有使用replaceInSheet

function runReplaceInSheet(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3");
  sheet.createTextFinder('datateam').replaceAllWith('42007860'); // Added
}

参考:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

我会检查模板,你的实际 XLS 文件。 在输入数据之前设置单元格的类型。 我认为这可能是您的问题,而不是您的实际代码。 这是在主页选项卡中。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM