Automate Spreadsheet Updates with Google Apps Script

I'm currently facing an issue while trying to paste csv data into a Google Sheet using the code provided below. Strangely, when I execute myFunction(), the data quickly appears in the Google Sheet but then vanishes instantly, almost as if sheet.clear() is being triggered unexpectedly. Interestingly, when I disable sheet.clear(), the data transference works perfectly fine. Any insights on why sheet.clear() might be misbehaving? This mystery has got me puzzled.

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);
}

Answer №1

When it comes to retrieving data from a spreadsheet right after writing it, it's important to ensure that all the expected data is actually accessible. One strategy I like to use is storing my data in arrays for as long as possible, allowing me to minimize read and write operations. However, if switching between functions makes this difficult, one approach could be passing data directly to subsequent functions to avoid unnecessary reads from the spreadsheet.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve the textFrame where the cursor is currently located?

While inputting text into a frame, I am looking to execute a script. I want this script to target the specific text frame where my cursor is located. How can I reference this particular textFrame using Javascript? ...

Pointer Permissions parsing does not permit creation

Despite meticulously following the instructions in this guide, I am encountering a 403 error when attempting to create a new row: Error code: 119 Error message: "This user does not have permission to carry out the create operation on Messages. This s ...

Highcharts experiencing difficulty in removing labels

How can I remove labels added to highcharts when a button is clicked, as they still remain visible? For reference, please check out the fiddle: https://jsfiddle.net/7pq3po3o/3/ HTML: <script src="https://code.highcharts.com/highcharts.js"></sc ...

Why isn't the nested intricate directive being executed?

After watching a tutorial on YouTube by John Lindquist from egghead.io, where he discussed directives as components and containers, I decided to implement a similar structure but with a more dynamic approach. In his example, it looked something like this ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

"Exploring the power of Vue3's composition API in managing the

Trying to implement an accordion component in Vue 3, but encountering a strange comparison issue. I'm attempting to execute a function within the accordionitem - specifically the toggle operation. However, despite numerous attempts, I am unable to mo ...

Displaying only a section of a webpage using AJAX

Currently, I am utilizing an ajax call to showcase a PHP page, which is functioning correctly as shown below: <script type="text/javascript"> var xhr = false; if (window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Verifying the existence of a user in my mongodb database before adding a new user to avoid multiple registrations with the same email address

Attempted to use Express, I am in the process of creating a .js file that manages POST requests and checks whether a user already exists before adding them to my MongoDB database. I set up two separate MongoClient connections for different scenarios: one t ...

Creating a seamless experience with Vue.js 3 and Bootstrap 5's Sticky Footer functionality

This template was created based on the Bootstrap 5 Sticky Footer and Nav example, but with a twist. I am implementing Vue.js 3 in my project, and encountered an issue where adding my custom script within the id="awApp" element caused the sticky footer func ...

Error with reference to JS file in IE versions 7 and 8

Encountering a strange issue on an ASP.NET page - the JavaScript file reference below functions correctly in IE6: <script src='~/Scripts/xxx.js' type="text/javascript"></script> However, it fails to work in IE7/8, resulting in an " ...

Tips on utilizing normalizr to flatten an array with various object types?

Upon receiving a JSON response from the server, it typically looks something like this: { data: [ { id: 1, type: 'person', emails: [ { id: 1 }, { id: 3 } ], phones: [] }, { id: 2, type: 'person', emails: [ { id: 2 } ], p ...

What is the best way to send an array to an ejs template within an express application?

I've been attempting to pass an array of objects to EJS views in Express, but I'm encountering issues. Here's what I have on the server side: var roominfo = function(roomname){ this.roomname=roomname; }; room_info_array= new Array(1); roo ...

Updating Variables Declared in Parent Component from a Child Component in React using NextJS - A Comprehensive Guide

After reviewing the tutorial on React: Reverse Data Flow to update the variables foodObj, input, and buttonClicked declared in the Parent Component file Main.js, using the child component <SearchAndSuggestion>, I encountered an issue. Here is a snipp ...

Determine whether a variable includes an alphabetic character

I need to eliminate any results from an array that include alphabetic characters. To do this, I am using the following code: if(gtin.toString().length != 13 || /[a-z\-]+/ig.test(gtin) == true) { gtin = "null"; } Although it works for some variab ...

Utilizing PHP file error messages in AJAX response: A comprehensive guide

I have the code snippet below for uploading a file: <a href="#" id="promotion_status_1"> <button type="button" class="btn btn-default brmodalbtn" data-toggle="modal" data-target="#BrandImageModal" id="1">On</button&g ...

The navigation bar is malfunctioning on Bootstrap 4.0.0-beta.2 framework

I have recently updated to the latest version of Bootstrap: "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5", "bootstrap": "^4.0.0-beta.2", "core-js": "^2.4.1", "jquery": "^3.2.1", "popper.js": "^1.12.9", As part of this update, I incorporated a navbar: &l ...

Removing a value from a JavaScript object

Looking to delete a specific value from an object with multiple values? This is how my object is structured: { 'how can i change my password?': [ 'how can I change my password?', 'how may I change my password?', ...

The system displayed an 'Error' stating that the variable 'index' is defined in the code but is never actually utilized, resulting in the (no-unused-vars) warning

I have configured eslint and eslint-plugin-react for my project. Upon running ESLint, I am encountering no-unused-vars errors for every React component in the codebase. It seems like ESLint is not properly identifying JSX or React syntax. Any suggestions ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...