在 Google 表格中自动生成唯一的顺序 ID

McC*_*ief 3 google-sheets google-apps-script

在 Google 表格中,我有一个名为 Events/Incidents 的电子表格,来自各个分支机构的员工都在其中。我希望 B 列根据 A 列中的年份和之前填充的事件自动生成唯一 ID。鉴于某一天可能有多个事件,A 列中的行可能有重复的日期。

以下是我在 B 列中查找的示例:

ID

不能有重复。非常感谢您对代码或公式的帮助。

con*_*rpw 7

有我的想法https://github.com/contributorpw/google-apps-script-snippets/blob/master/snippets/spreadsheet_autoid/autoid.js

主函数获取一张表并制作魔术

/**
 *
 * @param {GoogleAppsScript.Spreadsheet.Sheet} sheet
 */
function autoid_(sheet) {
  var data = sheet.getDataRange().getValues();
  if (data.length < 2) return;
  var indexId = data[0].indexOf('ID');
  var indexDate = data[0].indexOf('DATE');
  if (indexId < 0 || indexDate < 0) return;
  var id = data.reduce(
    function(p, row) {
      var year =
        row[indexDate] && row[indexDate].getTime
          ? row[indexDate].getFullYear() % 100
          : '-';
      if (!Object.prototype.hasOwnProperty.call(p.indexByGroup, year)) {
        p.indexByGroup[year] = [];
      }
      var match = ('' + row[indexId]).match(/(\d+)-(\d+)/);
      var idVal = row[indexId];
      if (match && match.length > 1) {
        idVal = match[2];
        p.indexByGroup[year].push(+idVal);
      }
      p.ids.push(idVal);
      p.years.push(year);
      return p;
    },
    { indexByGroup: {}, ids: [], years: [] }
  );

  // Logger.log(JSON.stringify(id, null, '  '));

  var newId = data
    .map(function(row, i) {
      if (row[indexId] !== '') return [row[indexId]];
      if (isNumeric(id.years[i])) {
        var lastId = Math.max.apply(
          null,
          id.indexByGroup[id.years[i]].filter(function(e) {
            return isNumeric(e);
          })
        );
        lastId = lastId === -Infinity ? 1 : lastId + 1;
        id.indexByGroup[id.years[i]].push(lastId);
        return [
          Utilities.formatString(
            '%s-%s',
            id.years[i],
            ('000000000' + lastId).slice(-3)
          )
        ];
      }
      return [''];
    })
    .slice(1);
  sheet.getRange(2, indexId + 1, newId.length).setValues(newId);
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我认为它可以在功能中简化。