因此,您希望每一行都有一个唯一的 ID。根据您的要求,您有多种选择。
方法一:简单的公式
如果您不更改顺序或删除(不仅仅是清空)行,则可以简单地使用列数作为设置 ID 的值。只需添加公式即可=ROW()
为其赋值。
方式2:使用UUID
如果您不关心它的值是什么,您可以使用 UUID。这将使其不依赖于其他行的值。您可以使用以下方式获得一个:
const uuid = Utilities.getUuid()
这是最通用的选择。
方式三:使用属性保存当前值
如果您需要它们是仅在使用脚本时设置的自动递增数字(即不手动添加 id),您可以使用属性来保留计数:
function getNextId() {
// Get properties
const properties = PropertiesService.getScriptProperties()
// Aquire the script lock. Prevents race condition
const lock = LockService.getScriptLock()
lock.waitLock(2000)
// Get the saved ID and save the next value
// Properties are string so it has to convert the type
const id = parseInt(properties.getProperty('id_seq') || 0)
properties.setProperty('id_seq', (id+1).toString())
// Release the script lock (allows other executions to continue)
lock.releaseLock()
// Return the result
console.log(id)
return id
}
要使用它,您可以像使用 UUID 一样调用它:
const id = nextID()
请注意,算法需要锁定以防止竞争条件(如果脚本同时在多个实例中执行)。
这类似于数据库上的序列。
方式4:最大+1
这将添加一个仅包含 ID 的新行。需要在添加数据之前使用。如果最大的数字被删除,相同的ID将被重新使用。请注意,我们还需要锁定整个操作,并且还需要刷新以 100% 确定另一个脚本会看到此脚本所做的更改。
function setNextId() {
// Get spreadsheet
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]
// Aquire the script lock. Prevents race condition
const lock = LockService.getScriptLock()
lock.waitLock(2000)
// Get value from last row
const lastCell = sheet.getRange(1, 1, sheet.getLastRow(), 1)
const values = lastCell.getValues()
.flat()
.filter(Number.isInteger)
const value = Math.max(...values)
// Create new row
const newCell = sheet.getRange(sheet.getLastRow()+1, 1)
newCell.setValue(value+1)
// Ensure value is added before releasing the lock
SpreadsheetApp.flush()
// Release the script lock (allows other executions to continue)
lock.releaseLock()
}
方式5:最后一行+1
与最后一个类似,但它看起来只是最后一行。这不支持对行重新排序。
function setNextId() {
// Get spreadsheet
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]
// Aquire the script lock. Prevents race condition
const lock = LockService.getScriptLock()
lock.waitLock(2000)
// Get value from last row
const lastCell = sheet.getRange(sheet.getLastRow(), 1)
const value = lastCell.getValue()
// Create new row
const newCell = lastCell.offset(1, 0)
newCell.setValue(value+1)
// Ensure value is added before releasing the lock
SpreadsheetApp.flush()
// Release the script lock (allows other executions to continue)
lock.releaseLock()
}
参考
- Utilities.getUuid()(Google Apps 脚本参考) https://developers.google.com/apps-script/reference/utilities/utilities#getuuid
- 锁定服务(Google Apps 脚本参考) https://developers.google.com/apps-script/reference/lock
- 属性服务(Google Apps 脚本参考) https://developers.google.com/apps-script/reference/properties/properties-service
- SpreadsheetApp.flush()(Google Apps 脚本参考) https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#flush
- 类范围(Google Apps 脚本参考) https://developers.google.com/apps-script/reference/spreadsheet/range