Write to multiple cells in Google sheets - javascript

is there anyway to write to multiple cells with just one line of code?
Instead of:
response_sheet.getRange("B1").setValue("Name");
response_sheet.getRange("B6").setValue("Evaluators:");
response_sheet.getRange("A9").setValue("Ownership");
something like:
response_sheet.getRange([["B1"],["B6"],["A9"]]).setValues([["Name","Evaluators","Ownership"]]);
The above gets me a "Range not found" error though. Cant find any working samples or documentation on whether this is possible.

Unfortunately, I think that there are no methods to directly import values to the discrete ranges in Class SpreadsheetApp. But if you want to import "Name","Evaluators" and "Ownership" to "B1","B6" and "A9" using getRange() and setValues(), you can use the following sample script.
SpreadsheetApp.getActiveSheet().getRange("A1:B9").setValues([["","Name"],["",""],["",""],["",""],["",""],["","Evaluators"],["",""],["",""],["Ownership",""]]);
If you want to use the method with higher readability, how about using Sheets API v4? In order to use this script, please enable Sheets API v4 at Advanced Google Services and API console.
Enable Sheets API v4 at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Google Sheets API v4
Enable Sheets API v4 at API console
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click Enable APIs and get credentials like keys.
At left side, click Library.
At Search for APIs & services, input "sheets". And click Google Sheets API.
Click Enable button.
If API has already been enabled, please don't turn off.
One liner sample :
Sheets.Spreadsheets.Values.batchUpdate({"data":[["sheet1!B1","Name"],["sheet1!B6","Evaluators"],["sheet1!A9","Ownership"]].map(function(e){return{"range":e[0],"values":[[e[1]]]}}),"valueInputOption":"USER_ENTERED"},"### spreadsheet ID ###");
Expanded one liner sample :
Sheets.Spreadsheets.Values.batchUpdate(
{
"data":[
["sheet1!B1","Name"], // Please input range (a1notation) and value.
["sheet1!B6","Evaluators"], // Please input range (a1notation) and value.
["sheet1!A9","Ownership"] // Please input range (a1notation) and value.
].map(function(e){
return{
"range":e[0],
"values":[[e[1]]]
}
}),
"valueInputOption":"USER_ENTERED"
},
"### spreadsheet ID ###" // Please input spreadsheet ID.
);
Note :
When you use this script, please input the ranges which are a1notation and values to above 2 dimensional array, and also spreadsheet ID.
When you use ["sheet1!B1","value1"],["sheet2!B1","value2"], you can import values to both sheets.
References :
Advanced Google Services : https://developers.google.com/apps-script/guides/services/advanced
Sheets API v4: https://developers.google.com/sheets/api/
If this is not useful for you, I'm sorry.

Related

How to track user clicks on Phaser web-game?

So I've made a web game with the Phaser.js framework. Without a database, I want to track events/actions in the game. The data consist of at least two strings: time_stamp & event (i.e. "click the 'Play' button").
My current attempt is to write the data to my google sheets. How to do that?
I want something like:
Function for 'Play' button
playGame() {
// Go to gameplay scene
scene.start(Gameplay)
// Script to insert data to google sheet
submitEvent(timestamp, "click the 'Play' button"){
}
}
Or maybe there's an easier way to do the tracking? Need to be a free service and capable to store data online with javascript.
I tried the Google Sheet API but was confused with the doc, it seems like I need the player to log in and authorize, is it possible to avoid that? Most tutorials use HTML Form to send data, which I didn't use.
I believe your goal is as follows.
You want to put the values of timestamp and "click the 'Play' button" to your Google Spreadsheet using Javascript without authorization process.
In the current stage, in order to put a value to Spreadsheet using Sheets API, it is required to use the access token retrieved from OAuth2 and the service account. I'm worried that in this case, the script might be a bit complicated, and it might not your expected direction.
If you want to put a value to your Spreadsheet with a simple script without the authorization process, how about using Web Apps created by Google Apps Script? When Web Apps is used, your goal might be able to be achieved. When the method for putting a value to Spread sheet with Web Apps is implemented in Javascript, please do the following flow.
Usage:
1. Create Spreadsheet.
Please create Spreadsheet. You can create a new Spreadsheet by accessing https://docs.google.com/spreadsheets/create. In this case, the Spreadsheet is created in the root folder of your Google Drive. And please open the script editor on Spreadsheet.
2. Prepare Google Apps Script.
Please copy and paste the following script to the script editor and save the script.
function doGet(e) {
const { value1, value2 } = e.parameter;
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].appendRow([value1, value2]);
return ContentService.createTextOutput("Done.");
}
3. Deploy Web Apps.
The detailed information can be seen in the official document.
Please set this using the new IDE of the script editor.
On the script editor, at the top right of the script editor, please click "click Deploy" -> "New deployment".
Please click "Select type" -> "Web App".
Please input the information about the Web App in the fields under "Deployment configuration".
Please select "Me" for "Execute as".
Please select "Anyone" for "Who has access".
Please click "Deploy" button.
When "The Web App requires you to authorize access to your data." is shown, please click "Authorize access" button. And, please authorize the scopes.
This authorization process is only one time. When you access Web Apps using Javascript, no authorization is required, because it has already been done here. I thought that this might be an important point to your expected direction.
Copy the URL of the Web App. It's like https://script.google.com/macros/s/###/exec. This URL is used for your HTML.
4. Testing.
When the values of value1 and value2 are timestamp and "click the 'Play' button", the sample script of Javascript is as follows. And, please set your Web Apps URL. And, please use this script in your script.
function sample(value1, value2) {
const webAppsURL = "https://script.google.com/macros/s/###/exec"; // Please set your Web Apps URL.
fetch(`${webAppsURL}?value1=${value1}&value2=${value2}`).then(async (res) => console.log(await res.text()));
}
When you run sample(value1, value2) by giving the values, the values are put to the 1st sheet of the Spreadsheet.
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script (Author: me)

How does the code of Google Analytics filter the data that measures product detail views?

Let's say that I want to write a program that measures the product detail views exactly like Google Analytics does. Do we know the code of it by using the standard bigQuery Export Schema ?
I undestand that Google Analytics is written in Javascript, but SQL, Python and PySpark versions will be fine too.
For some reason, by checking the data coming from the export schema, if I write the query
SELECT COUNT(*) FROM bigQuery WHERE hits.contentGroup.contentGroup1 = 'product details page'
I get a count of 2300 while in GA I get 1500, so I need to know what filters does Google Analytics put in order to filter the data.

How to migrate google sheets API v3 to google sheets Api v4

I've been using a public google spreadsheet as a JSON endpoint for several of my web projects for some time now. I liked this approach because I could retrieve data from a public spreadsheet without needing any kind of authentication or tokens to get the data, all I needed to do was publish the spreadsheet and then fetch from a simple URL:
fetch(`https://spreadsheets.google.com/feeds/${mode}/${id}/${sheetNum}/public/values?alt=json`).then((res)=>console.log(res));
Google is deprecating sheets v3, and I'm confused about how to migrate to v4. From this answer I gather that I need to provide an access token which is created via the google cloud console. But do I need to create some kind of special "app" or "workplace" or will any old API token do? I tried the following:
Create a GCP project
Enable Google Sheets API
Hit Create Credentials
fetch data using the following URL scheme:
fetch(https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/RANGE?key=API_KEY)
But this is giving me a 403 response.
You are using the JSON Alt Type variant of the Google Data protocol. This protocol is dated and appears to no longer work reliably. The GData API Directory tells:
Google Spreadsheets Data API: GData version is still live. Replaced by the Google Sheets API v4.
Google Sheets API v4 is a modern RESTful interface that is typically used with a client library to handle authentication and batch processing of data requests. If you do not want to do a full-blown client implementation, David Kutcher offers the following v4 analog for the GData JSON Alt Type, using jQuery:
GData (old API, not recommended):
var url = 'https://spreadsheets.google.com/feeds/list/' +
spreadsheet_id + '/' + tab_ordinal + '/public/values?alt=json';
($.getJSON(url, 'callback=?')).success(function(data) {
// ...
};
V4 (new API, recommended):
var url = 'https://sheets.googleapis.com/v4/spreadsheets/' +
spreadsheet_id + '/values/' + tab_name +
'?alt=json&key=' + api_key;
($.getJSON(url, 'callback=?')).success(function(data) {
// ...
};
...where:
spreadsheet_id is the long string of letters and numbers in the address of the spreadsheet — it is the bit between /d/ and /edit
tab_ordinal is number of the sheet — the first sheet that appears in the tab bar is sheet number 1, the second one is 2, and so on
tab_name is the name of the sheet, i.e., the name you see in the tab bar at the bottom of the window when you have the spreadsheet open for editing
api_key is the API key you get from from Google Cloud Platform console
Note that the JSON output format differs between the two versions.
The old GData JSON Alt Type variant API requires that the spreadsheet is made public through File > Publish to the web. V4 requires that the file is shared with "anyone with the link can view" through File > Share.
FINDINGS
The URL scheme produces the error 403 because mostly likely the spreadsheet file isn't shared publicly like this:
I can also replicate the 403 error when my test sheet isn't shared publicly using the same URL scheme:
RECOMMENDATION:
You can double check the spreadsheet file you're accessing and check it's sharing permission, making sure it's set to Anyone with the link:
TEST RESULT
Publicly shared test sheet
After setting up the spreadsheet file's sharing permission to Anyone with the link using the same v4 URL scheme:

Cant find the Gmaps API in CodeIgniter Environment

Good Day to you,
I have a difficulty in finding the google maps api key. I had to change the base_url in the config file and since then it gives me this error:
Google Maps API error: MissingKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#missing-key-map-error_.ab # js?v=3.exp&signed_in=false&sensor=false&libraries=places&language=en-USA:32
util.js:211
Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
util.js:211
Google Maps API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required
if i add this tag with my api key into the <head> of the page: <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" type="text/javascript"></script>
i get this error:
unfortunately i only have an img of the error right now.
first it was missing then it was duplicated. and why would it be missing if i change the config?i know that you have to get a new api key with the new domain and i did that but there is a conflict with the old api key which i cant find anywhere. where then would i find the original key? i tried searching in all the files couldnt find any key. does somebody have a hint for me? i tried searching all files for "googleapis.com". Maybe the there is an otherway to link to the google api of which i dont know. im really looking forward to get this fixed.
thank you for your time to read this and i hope someone can help me
regards
theweeezel
As the error stated :
The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key. If you are a Premium Plan customer, you must use either a client parameter with your client ID or a key parameter with a valid API key.
If you will check the guide to API keys and client IDs. Kindly double check the API Key created and follow the script tag below.
If you're using the API under the standard plan, you must use a browser key (a type of API key) set up in a project of your choice.
Specify a key when loading the API
To specify a key, include it as the value of a key parameter when loading the API.
For example:
NOTE:
Google Maps APIs are available for Android or iOS apps, Web browsers, and via HTTP web services. APIs in each platform require a specific type of key. The Google Maps JavaScript API will only work with a Browser key. APIs of the same platform can use the same key.
Hope this helps.

How can I access Google Sheet spreadsheets only with Javascript?

I want to access Google Spreadsheets using JavaScript only (no .NET, C#, Java, etc.)
I came here and was shocked to know that there is NO API for JavaScript to access Google Sheets.
Please tell me how to access (CREATE/EDIT/DELETE) Google Sheets using JavaScript or any of its frameworks like jQuery.
I have created a simple javascript library that retrieves google spreadsheet data (if they are published) via the JSON api:
https://github.com/mikeymckay/google-spreadsheet-javascript
You can see it in action here:
http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html
Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.
It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 2 (correction, 3) ways to do this today:
As mentioned in the answer by Dan Dascalescu, you can use Google Apps Script, the JavaScript-in-Google's-cloud solution. That is, non-Node server-side JS apps outside the browser that run on Google servers.
You code your apps in the Apps Script code editor, and they can access Google Sheets in two different ways:
The Spreadsheet Service (native object support; usage guide); native is easier but is generally older than...
The Google Sheets Advanced Service (directly access the latest Google Sheets REST API [see below]; usage guide)
Apps Script also powers add-ons, and you can extend Sheets UI functionality with Sheets add-ons (like these)
You can even write mobile add-ons which extend the Sheets app on Android
To learn more about using Apps Script, check out these videos I've created (most involve the use of Sheets)
You can also use the Google APIs Client Library for JavaScript to access the latest Google Sheets REST API on the client side.
Here are some generic samples of using the client library
The latest Sheets API (v4) was released at Google I/O 2016; it's much more powerful than all previous versions, giving developers programmatic access to most features found in the Sheets UI
Here is the JavaScript quickstart for the API to help you get started
Here are sample "recipes" (JSON payloads) for core API requests
If you're not "allergic" to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with more "real-world" samples of using the API you can learn from and migrate to JS if desired (NOTE: even though it's Python code, most API requests have JSON & easily portable to JS):
Migrating SQL data to a Sheet (code deep dive post)
Formatting text using the Sheets API (code deep dive post)
Generating slides from spreadsheet data (code deep dive post)
Those and others in the Sheets API video library
The 3rd way to access Google APIs with JavaScript is from the Node.js client library on the server-side. It works similarly to using the JavaScript (client) client library described just above, only you'll be accessing the same API from the server-side. Here's the Node.js Quickstart example for Sheets. You may find the Python-based videos above to be even more useful as they too access the API from the server-side.
When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.
Here's the Gist.
You can create a spreadsheet using the Google Sheets API. There is currently no way to delete a spreadsheet using the API (read the documentation). Think of Google Docs API as the route to create and look-up documents.
You can add/remove worksheets within the spreadsheet using the worksheet based feeds.
Updating a spreadsheet is done through either list based feeds or cell based feeds.
Reading the spreadsheet can be done through either the Google Spreadsheets APIs mentioned above or, for published sheets only, by using the Google Visualization API Query Language to query the data (which can return results in CSV, JSON, or HTML table format).
Forget jQuery. jQuery is only really valuable if you're traversing the DOM. Since GAS (Google Apps Scripting) doesn't use the DOM jQuery will add no value to your code. Stick to vanilla.
I'm really surprised that nobody has provided this information in an answer yet. Not only can it be done, but it's relatively easy to do using vanilla JS. The only exception being the Google Visualization API which is relatively new (as of 2011). The Visualization API also works exclusively through a HTTP query string URI.
There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.
First up, you need an Google API key. Head here:
https://developers.google.com/places/web-service/get-api-key
NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037
Get all data for a spreadsheet - warning, this can be a lot of data.
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true
Get sheet metadata
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}
Get a range of cells
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}
Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.
var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";
axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2016 update: The easiest way is to use the Google Apps Script API, in particular the SpreadSheet Service. This works for private sheets, unlike the other answers that require the spreadsheet to be published.
This will let you bind JavaScript code to a Google Sheet, and execute it when the sheet is opened, or when a menu item (that you can define) is selected.
Here's a Quickstart/Demo. The code looks like this:
// Let's say you have a sheet of First, Last, email and you want to return the email of the
// row the user has placed the cursor on.
function getActiveEmail() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var activeRow = activeSheet.getActiveCell().getRow();
var email = activeSheet.getRange(activeRow, 3).getValue();
return email;
}
You can also publish such scripts as web apps.
edit: This was answered before the google doc's api was released. See Evan Plaice's answer and Dan Dascalescu's answer for more up-to-date
information.
It looks lke you can, but it's a pain to use. It involves using the Google data API.
http://gdatatips.blogspot.com/2008/12/using-javascript-client-library-w-non.html
"The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API."
and an example of writing a gadget that interfaces with spreadsheets: http://code.google.com/apis/spreadsheets/gadgets/
'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs
http://code.google.com/apis/spreadsheets/gadgets/
http://code.google.com/apis/gdata/docs/js.html
http://www.mail-archive.com/google-help-dataapi#googlegroups.com/msg01924.html
May be these would help you out..
Sorry, this is a lousy answer. Apparently this has been an issue for almost two years so don't hold your breath.
Here is the official request that you can "star"
Probably the closest you can come is rolling your own service with Google App Engine/Python and exposing whatever subset you need with your own JS library. Though I'd love to have a better solution myself.
In this fast changing world most of these link are obsolet.
Now you can use Google Drive Web APIs:
Java
PHP
Javacript
.NET
Python
Ruby
and others...
you can do it by using Sheetsee.js and tabletop.js
example from git
another Example
You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:
https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html
Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).
Some example code (this example makes an RGraph chart):
<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>
<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>
<script>
// Create a new RGraph Sheets object using the spreadsheet's key and
// the callback function that creates the chart. The RGraph.Sheets object is
// passed to the callback function as an argument so it doesn't need to be
// assigned to a variable when it's created
new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
{
// Get the labels from the spreadsheet by retrieving part of the first row
var labels = sheet.get('A2:A7');
// Use the column headers (ie the names) as the key
var key = sheet.get('B1:E1');
// Get the data from the sheet as the data for the chart
var data = [
sheet.get('B2:E2'), // January
sheet.get('B3:E3'), // February
sheet.get('B4:E4'), // March
sheet.get('B5:E5'), // April
sheet.get('B6:E6'), // May
sheet.get('B7:E7') // June
];
// Create and configure the chart; using the information retrieved above
// from the spreadsheet
var bar = new RGraph.Bar({
id: 'cvs',
data: data,
options: {
backgroundGridVlines: false,
backgroundGridBorder: false,
xaxisLabels: labels,
xaxisLabelsOffsety: 5,
colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
yaxis: false,
marginLeft: 40,
marginBottom: 35,
marginRight: 40,
key: key,
keyBoxed: false,
keyPosition: 'margin',
keyTextSize: 12,
textSize: 12,
textAccessible: false,
axesColor: '#aaa'
}
}).wave();
});
</script>
For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.

Categories

Resources