Google Apps Script提交表单至表格时ID参数无效错误排查求助
The Problem
You're trying to push form data into Google Sheets via Apps Script, but hitting this error:
{"result": "error", "Error in: ": {"message": "Invalid argument: id", "name": "Exception", "fileName": "Code", "lineNumber": 20, "smack": "\that Code:20 (handleResponse)\n\tat Code:2 (doGet)\n" }}
Here's the script you're working with:
function doGet(e){ return handleResponse(e); } // Enter sheet name where data is to be written below var SHEET_NAME = "Table"; var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service function handleResponse(e) { // shortly after my original solution Google announced the LockService[1] // this prevents concurrent access overwritting data // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html // we want a public lock, one that locks for all invocations var lock = LockService.getPublicLock(); lock.waitLock(30000); // wait 30 seconds before conceding defeat. try { // next set where we write the data - you could write to multiple/alternate destinations var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key")); var sheet = doc.getSheetByName(SHEET_NAME); // we'll assume header is in row 1 but you can override with header_row in GET/POST data var headRow = e.parameter.header_row || 1; var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var nextRow = sheet.getLastRow()+1; // get next row var row = []; // loop through the header columns for (i in headers){ if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column row.push(new Date()); } else { // else use header name to get data row.push(e.parameter[headers[i]]); } } // more efficient to set values as [][] array than individually sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // return json success results return ContentService .createTextOutput(JSON.stringify({"result":"success", "row": nextRow})) .setMimeType(ContentService.MimeType.JSON); } catch(e){ // if error return this return ContentService .createTextOutput(JSON.stringify({"result":"error", "error": e})) .setMimeType(ContentService.MimeType.JSON); } finally { //release lock lock.releaseLock(); } } function setup() { var doc = SpreadsheetApp.getActiveSpreadsheet(); SCRIPT_PROP.setProperty("key", doc.getId()); }
Why This Happens & How to Fix It
That error points straight to line 20: var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key")); — the script is trying to open a sheet with an invalid or missing ID. Here's how to diagnose and fix this:
1. Did you run the setup() function?
The setup() function is supposed to store your spreadsheet's ID in the script's properties. If you never ran it, the "key" property doesn't exist, so openById() gets an empty value.
- Quick fix: In the Apps Script editor, select the
setupfunction from the dropdown at the top, then click the run button (▶️). You'll have to authorize the script the first time — just follow the prompts (you might need to click "Advanced" > "Go to [Script Name]" to bypass the safety warning).
2. Verify the stored sheet ID is correct
Let's check what's actually stored in the script properties:
- Add this temporary debug function to your script:
function checkStoredID() { var storedID = SCRIPT_PROP.getProperty("key"); console.log("Stored Sheet ID:", storedID); // Test if the ID works try { var testSheet = SpreadsheetApp.openById(storedID); console.log("Success! Sheet name:", testSheet.getName()); } catch (err) { console.log("Failed to open sheet:", err.message); } } - Run it, then go to View > Logs to see the output. If the stored ID is empty or doesn't match your sheet's actual ID, that's the problem.
- How to get your sheet's ID: Open your Google Sheet, look at the URL — it's the long random string between
/d/and/edit(e.g.,https://docs.google.com/spreadsheets/d/abc123xyz123/edit→ ID isabc123xyz123).
3. Double-check your sheet name
While not the cause of this specific error, make sure SHEET_NAME = "Table" matches the exact name of your sheet tab (it's case-sensitive!). If the name is wrong, you'll hit another error once the ID is fixed, so better to confirm now.
4. Debug incoming form data (optional)
If you're still having issues after fixing the ID, add a log to check if your form data is being passed correctly:
// Inside handleResponse(), right after acquiring the lock console.log("Received form data:", e.parameter);
Run the script again, check the logs, and confirm the parameters match your sheet's header names.
Self-Diagnosis Tips for Future Issues
- Always check execution logs: The Apps Script editor's logs (View > Logs) are your best friend — they show exactly where errors happen and why.
- Test incrementally: Instead of running the whole script at once, test small parts first (e.g., hardcode the sheet ID to confirm you can open it, then add the script property retrieval, then handle form data).
- Use
console.log()liberally: Log variables and values at key points to see what's going on under the hood.
内容的提问来源于stack exchange,提问作者Frost0x




