首页 > 解决方案 > 如果名称在列中,则将该列转换为日期格式 Google 表格

问题描述

语境

我想将下面各列中的数据格式动态更改为适当的日期格式:我使用了这段代码,但现在想让它动态化。日期列中的原始数字格式是来自谷歌财经的日期/时间格式。但我只想要 dd/mm/yyyy 的格式。

在此处输入图像描述

这是我的原始代码:

function Dateformats() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  // Within the values copied spreadsheet, columns that have 'Date' will be the subject of this function
  var sheet = spreadsheet.getSheetByName('Values (Live Data copied)')
 // var sheet = spreadsheet.getSheetByName("Values (Live Data copied)")
  var dataList = sheet.getRangeList(['A:A', 'C:C', 'E:E', 'G:G', 'I:I', 'K:K', 'M:M', 'O:O']);
    dataList.setNumberFormat('dd/MM/yyyy');

}

动态结果的新代码

  function Dateformats() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  // Within the values copied spreadsheet, columns that have 'Date' will be the subject of this function
  var range = spreadsheet.getRangeByName('Values (Live Data copied)!Date')
 
  if(range !== null){
    range.setNumberFormat('dd/MM/yyyy');
  }
}

两者都有效,尽管后者实际上并没有出现在工作表上。日期格式仍然保持不变。

问题

有人知道动态重新格式化包含“日期”的列的修复方法吗?

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


解释:

您的目标是确定列是否包含日期对象。如果它包含一个日期对象,您希望将日期的格式从时间戳更改为日期。

以下脚本:

  • 将根据行确定每列的类型,如果类型是日期或其他类型4th,它将返回。我使用map根据此条件检查日期元素:truefalse

    typeof em.getMonth === 'function'

  • forEach类型的列date设置整列的格式。

解决方案:

function Dateformats() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spreadsheet.getSheetByName('Values (Live Data copied)')
  const checkTypes = sheet.getRange(4,1,1,sheet.getLastColumn()).
                   getValues().
                   flat().
                   map(em=>typeof em.getMonth === 'function');
  checkTypes.forEach((ct,i)=>{
        if(ct){
           sheet.getRange(4,i+1,sheet.getMaxRows(),1).
           setNumberFormat('dd/MM/yyyy');
        }
  });
}

请再次注意,我使用4th行来确定每一列的类型。因此,该行应包含与同一列中的其余单元格相同的类型。即,如果列包含多种类型的数据,则该解决方案将不起作用。


推荐阅读