从 json 添加多行而不是单行

Append multiple row instead of single row from json

我有脚本可以将 json 数据复制到 google sheet,bus 有没有办法附加多行而不是单行

谁能解释一下我是如何修改这个脚本的?谢谢

function doPost(request = {}) {
  const { parameter, postData: { contents, type } = {} } = request; //request data
  const { dataReq = {} } = JSON.parse(contents); //content
  const { fname = {} } = JSON.parse(contents); //function name

  const response = {
    status: "function not found: " + fname, // prepare response in function not found
    data2: dataReq
  }
  switch (fname) { //function selection
    case 'pasteData':
      var output = JSON.stringify(pasteDAta(dataReq)) //call function with data from request
      break
    default:
      var output = JSON.stringify(response)
      break
  }
  return ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON); //response to frontend
}
function pasteDAta(dataReq) {
  const id = '1_27rjNQmlXrwVKpLWUbGrJYPJufGRa7Dk-XEKcNAHr0'; //id of Google Sheet
  var sheet = SpreadsheetApp.openById(id).getSheetByName('Sheet1'); //sheet
  var headings = sheet.getDataRange().getValues()[0]; //Headers
  var i = 0 //to test the times that efectively adds rows the forEach function
  
  dataReq.forEach((a) => { //go trought every item on dataReq as 'a'
    let holder = []; //to steore temp the elements
    for (x in headings) { //to add in order of Headers on sheet
      let output = (headings[x] in a) ? a[headings[x]] : ''; //if exist add, if not empty
      holder.push(output); //add to holder
    }
    sheet.appendRow(holder); //put holder(order data) on sheet
    i += 1 //to test the times
  });
  return "Numbers of sheets added: "+i;
}

在你的脚本中,做如下修改怎么样?

发件人:

var i = 0 //to test the times that efectively adds rows the forEach function

dataReq.forEach((a) => { //go trought every item on dataReq as 'a'
  let holder = []; //to steore temp the elements
  for (x in headings) { //to add in order of Headers on sheet
    let output = (headings[x] in a) ? a[headings[x]] : ''; //if exist add, if not empty
    holder.push(output); //add to holder
  }
  sheet.appendRow(holder); //put holder(order data) on sheet
  i += 1 //to test the times
});
return "Numbers of sheets added: "+i;

收件人:

var values = dataReq.map((a) => {
  let holder = [];
  for (x in headings) {
    let output = (headings[x] in a) ? a[headings[x]] : '';
    holder.push(output);
  }
  return holder;
});
var len = values.length;
sheet.getRange(sheet.getLastRow() + 1, 1, len, values[0].length).setValues(values);
return "Numbers of sheets added: " + len;
  • 在此修改中,使用map代替forEach。并且,返回一个二维数组。该数组使用 setValues.
  • 附加到 sheet

注:

  • 当您修改 Google Apps 脚本时,请将部署修改为新版本。这样,修改后的脚本就会反映在 Web Apps 中。请注意这一点。

  • 您可以在“Redeploying Web Apps without Changing URL of Web Apps for new IDE”的报告中看到详细信息。

  • 如果这个修改不能直接解决你的问题,当你提供dataReq的示例值时,我认为这有助于思考修改点。

参考文献: