简体   繁体   English

BatchUpdate Google Apps 脚本正在自动清除工作表

[英]BatchUpdate Google Apps Script is clearing sheet automatically

I'm working on pasting some csv data into a google sheet and have the code below.我正在将一些 csv 数据粘贴到谷歌表中,并具有以下代码。 For some reason, when I run myFunction(), the data flashes into the Google Sheet, but then disappears instantly, almost as if sheet.clear() is being called.出于某种原因,当我运行 myFunction() 时,数据会闪现到 Google 表格中,但随后立即消失,几乎就像在调用 sheet.clear() 一样。 When I comment out sheet.clear(), the data copies over just fine.当我注释掉 sheet.clear() 时,数据复制过来就好了。 Any ideas why sheet.clear() might be called out of order?任何想法为什么 sheet.clear() 可能会被乱序调用? I can't figure it out.我想不通。

function myFunction(){
  var spreadsheetId = 'some Id'
  var csvFileId = 'some Id'
  var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName('Sheet1');
  sheet.clear();
  
  getCSVData(csvFileId, spreadsheetId);
}

function getCSVData(csvFileId, spreadsheetId){
  var data = DriveApp.getFileById(csvFileId)
  .getBlob()
  .getDataAsString();
  var sheetId = SpreadsheetApp.openById(spreadsheetId)
  .getSheets()[0]
  .getSheetId();
    
  var resource = {
    requests: [
      {
        pasteData: {
          data: data,
          coordinate: { sheetId: sheetId,
                       rowIndex: 0,
                       columnIndex: 0 },
          type: 'PASTE_VALUES',
          delimiter: ","
        },
      }
    ],
    includeSpreadsheetInResponse: true,
  };
  Sheets.Spreadsheets.batchUpdate(resource, spreadsheetId);
}

Whenever you are reading the data from a spreadsheet immediately after a write you should consider using SpreadsheetApp.flush() to insure that all of the data that you expect to be there is actually readable.每当您在写入后立即从电子表格中读取数据时,您应该考虑使用 SpreadsheetApp.flush() 以确保您期望存在的所有数据实际上都是可读的。 I prefer keeping my data in arrays as long as possible so that I can typically perform one read and write.我更喜欢将我的数据尽可能长时间地保存在 arrays 中,这样我通常可以执行一次读取和写入。 But if you switch from one function to another that may not be possible.但是,如果您从一个 function 切换到另一个可能是不可能的。 One option could be to pass data directly to sequential functions so that they don't have to read the data again from the spreadsheet.一种选择是将数据直接传递给顺序函数,这样它们就不必再次从电子表格中读取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM