我使用以下代碼將表單中的資料插入到谷歌表格中。它作業正常并正確添加資料。問題是當我想將資料添加到不在我的作業表上的列時。我知道我必須檢查作業表中是否存在這樣的列。如果它不存在,請添加它。然后才添加一行新資料。不幸的是,我是 Apps Script 的新生,我不知道該怎么做
// In case you want to change the Sheet name
var sheetName = 'xyz'
var scriptProp = PropertiesService.getScriptProperties()
// Lowercasing all input keys in the POST data by default (to avoid Message vs message confusion)
var shouldLowerCaseHeaders = true
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function filterRow (parameters, mandatoryFields) {
return mandatoryFields.every(field => parameters[field.toString().toLowerCase()] && parameters[field.toString().toLowerCase()].length > 0)
}
function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)
// Uncomment and add fields which must be mandatory when submitting a form
//const mandatoryFields = ['questions']
const mandatoryFields = []
try {
// Get the current open Google Sheet
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
// IMPORTANT: Create headers in your google sheet first
// If you dont create headers this won't match the data
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() 1
var parameters = e.parameter;
// Lower casing header keys - True by default
if (shouldLowerCaseHeaders){
Object.entries(e.parameter).map(([key, value]) => parameters[key.toString().toLocaleLowerCase()] = value)
}
const shouldInsertToSheet = filterRow(parameters, mandatoryFields)
if (shouldInsertToSheet){
var newRow = headers.map(function(header) {
return header.toString().toLowerCase() === 'timestamp' ? new Date() : parameters[header.toString().toLowerCase()]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
}
return HtmlService.createHtmlOutput("post request received");
}
catch (e) {
return HtmlService.createHtmlOutput("post request received");
}
finally {
lock.releaseLock()
}
}
如何檢查列標題是否存在,如果不添加標題列?
uj5u.com熱心網友回復:
如果要添加初始值中未包含的標題,只需將您擁有的標題與新串列進行比較,如果不包含任何屬于新串列的標題,請將它們添加到標題的末尾。
假設您的表的標題是這些:
| 頁眉1 | 頁眉2 | 頁眉3 | 頁眉4 |
|---|
Code.gs
const sS = SpreadsheetApp.getActiveSheet()
function appendHeaderIfNotExist(headersResponse) {
const actualHeaders = sS.getRange(1, 1, 1, sS.getLastColumn()).getValues().flat()
headersResponse.forEach(h => {
if (!actualHeaders.includes(h)) sS.getRange(1, sS.getLastColumn() 1).setValue(h)
})
}
function testImplementation() {
appendHeader(['Header1', 'Header5'])
}
運行函式后appendHeaderIfNotExist:
| 頁眉1 | 頁眉2 | 頁眉3 | 頁眉4 | 標題 5 |
|---|
您將不得不調整它以在您的腳本中作業,可能通過決議回應的內容并使用回應的鍵陣列呼叫函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/466568.html
