简体   繁体   中英

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. 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. When I comment out sheet.clear(), the data copies over just fine. Any ideas why sheet.clear() might be called out of order? 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. I prefer keeping my data in arrays as long as possible so that I can typically perform one read and write. But if you switch from one function to another that may not be possible. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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