不要在 Google 表格中添加已经存在的数据。

huangapple go评论135阅读模式
英文:

Don't add data if its already in google sheet

问题

Sure, here's the translated code portion:

JavaScript部分:

if (performance.navigation.type != performance.navigation.TYPE_RELOAD) {
  const queryParameters = Object.fromEntries(new URLSearchParams(window.location.search));

  const scriptURL = 'https://script.google.com/macros/s/script/exec';

  const data = new FormData();
  Object.entries(queryParameters).forEach(e => data.append(...e));
  fetch(scriptURL, { method: 'POST', body: data })
    .then(response => console.log('Success!', response))
    .catch(error => console.error('Error!', error.message))
}

Google Script部分:

var sheetName = 'Sheet1';
var scriptProp = PropertiesService.getScriptProperties();

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  scriptProp.setProperty('key', activeSpreadsheet.getId());
}

function doPost (e) {

  const { Name, Email, sample } = e.parameter;
  if (sample == "delete") {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
    var ranges = sheet.getDataRange();
    var values = ranges.getValues().filter(r => ![Name, Email].every(e => r.includes(e)));
    if (values.length == 0) {
      return ContentService.createTextOutput(`"${email}" was not found.`);
    }
    ranges.clearContent().offset(0, 0, values.length, values[0].length).setValues(values);
    return ContentService.createTextOutput(`Rows including "${Email}" were deleted.`);
  }

  var lock = LockService.getScriptLock();
  lock.tryLock(10000);

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
    var sheet = doc.getSheetByName(sheetName);

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;

    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header];
    });

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON);
  } catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON);
  } finally {
    lock.releaseLock();
  }
}

请注意,我已经根据您提供的代码进行了翻译,不包括问题部分。如果需要进一步的帮助,请告诉我。

英文:

Currently I have parameters being added to my google sheet on page load.

The URL looks like https://example.com/page?Name=John&Email=john@gmail.com

I'm wondering how I can stop this data being added a second time if people visit this URL again.

I currently stop a resubmission on page reload, but this doesn't stop a user if the URL is placed in a new tab, or opened on another device.

Is there a way to check if the same parameters are already in the sheet, and stop it being added if it is.

Javascript:

if (performance.navigation.type != performance.navigation.TYPE_RELOAD) {
const queryParameters = Object.fromEntries(new URLSearchParams(window.location.search));
const scriptURL = 'https://script.google.com/macros/s/script/exec';
const data = new FormData();
Object.entries(queryParameters).forEach(e => data.append(...e));
fetch(scriptURL, { method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
}

Google Script

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
const { Name, Email, sample } = e.parameter;
if (sample == "delete") {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var ranges = sheet.getDataRange();
var values = ranges.getValues().filter(r => ![Name, Email].every(e => r.includes(e)));
if (ranges.length == 0) {
return ContentService.createTextOutput(`"${email}" was not found.`);
}
ranges.clearContent().offset(0, 0, values.length, values[0].length).setValues(values);
return ContentService.createTextOutput(`Rows including "${Email}" were deleted.`);
}
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'Timestamp' ? new Date() : e.parameter[header]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}

I hope that makes sense, I am happy to clarify.

Thank you.

答案1

得分: 1

从:

try {
  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
  var sheet = doc.getSheetByName(sheetName)

到:

try {
  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
  var sheet = doc.getSheetByName(sheetName)
  var values = sheet.getDataRange().getValues().filter(r => [Name, Email].every(e => r.includes(e)));
  if (values.length > 0) {
    return ContentService.createTextOutput("Values were not appended.");
  }
  • 通过这个修改,当NameEmail的值存在时,脚本会停止。

注意:

参考资料:

英文:

In your script, how about the following modification?

From:

try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)

To:

try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var values = sheet.getDataRange().getValues().filter(r => [Name, Email].every(e => r.includes(e)));
if (values.length > 0) {
return ContentService.createTextOutput("Values were not appended.");
}
  • By this modification, when the values of Name and Email are existing, the script is stopped.

Note:

References:

huangapple
  • 本文由 发表于 2023年5月25日 15:13:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定