just wondering if there is a script to import data from google trends into a google sheet.
Basically, I would like to trigger such script daily to know the rising trends for a given topic and I am not sure if there is such solution available.
Else, is there any solution to perform this task?
Many thanks!
You may refer with this sample code snippet on how to use Google Apps Script for querying Google trends. For example, this function read input from the spreadsheet and sanitize it, then call up queryGoogleTrends to perform actual query and finally display the actual result:
function startQuery() {
sheet = SpreadsheetApp.getActiveSpreadsheet();
// start the query
var result = buildQueryString(sheet.getRangeByName("q").getValue(),
sheet.getRangeByName("cat").getValue(),
sheet.getRangeByName("geo").getValue(),
sheet.getRangeByName("gprop").getValue(),
sheet.getRangeByName("cmpt").getValue(),
sheet.getRangeByName("date").getValue()
);
// display the resulting link in a cell
sheet.getRangeByName("Query_Result").setValue(result).setBackground("yellow");
var csv_result = generateCsvDownload(sheet.getRangeByName("q").getValue(),
sheet.getRangeByName("cat").getValue(),
sheet.getRangeByName("geo").getValue(),
sheet.getRangeByName("gprop").getValue(),
sheet.getRangeByName("cmpt").getValue(),
sheet.getRangeByName("date").getValue()
);
sheet.getRangeByName("CSV_Download_Link").setValue(csv_result).setBackground("yellow");
}
Related
I have a Google Sheet that uses an IMPORTRANGE query to combine data from multiple other sheets. This combined import sheet is read by Google AppSheet. We have realized that the data AppSheet is reading is always outdated. It only reads the data as of the last time the sheet was manually opened.
I followed the steps in this post to try to fix this issue by creating this function: function refresh() {SpreadsheetApp.flush()}. I then set up a timed trigger to activate it once an hour. Logs show the function is running, but the data is still not updating until I manually open the sheet.
This is my first time using Apps Script. Any tips/ideas? Is there a different or better way to have the formulas update without opening the file?
Thank you for reading.
SpreadsheetApp.flush() only works for the script execution that calls it. If you need to refresh the data results from a formula it's uncertain how exactly the spreadsheet will respond as most of the formula calculations are done on the client side. You could verify this by yourself by using your web browser developer tools.
Anyway, spreadsheet formulas have several caveats so it will not be extrange that at some point you will have to rethink your solution. Assuming that you want to keep using AppSheet:
Use AppSheet for your front end and some no-code / low-code automation. Keep your app small, if you need many forms / views consider to distribute them among several apps.
Use Google Sheets only for data storage for your AppSheet app. Please bear in mind that it has 10 million cells limit for the whole spreadsheet, so you might want to delete the unused sheets and delete the unused columns and rows on each sheet.
You might use Google Apps Script to do the data import and transformation tasks. If you need that something be updated based on actions done on the AppSheet app, you might use an installable change trigger or use webhook from the AppSheet side to and a "simple" web application using Google Apps Script (you could use GET / POST http requests to trigger some Google Apps Script functions).
Also you might use other programming platforms for the data import / transformation tasks and keep using Google Sheets as your AppSheet database by using the Google Sheets API or other automation tools like Zappier, IFTTT, Integromat among many others.
solution #1
You can try this solution :
define a checkbox (for instance in A1 in tab Sheet1)
set this script
function myFunction() {
var chk = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange('A1')
chk.setValue(false);
SpreadsheetApp.flush();
Utilities.sleep(500);
chk.setValue(true);
}
define a trigger on it
define the formula as follows
=if(A1,importrange("1n-rjSYb63Z2jySS3-M0BQ78vu8DTPOjG-SZM4i8IxXI","A:Z"),"")
when A1 is unchecked, the result will be empty, then check A1 to fill once again the result as expected
solution #2
by script, try for instance
function myFunction() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet9')
var data = SpreadsheetApp.openById('1n-rjSYb63Z2jySS3-M0BQ78vu8DTPOjG-SZM4i8IxXI').getSheets()[0].getDataRange().getValues()
sh.getRange(1,1,data.length,data[0].length).setValues(data)
}
put a daily triger as needed
I feel like a bit of a chump, but I cannot work this out...
I have been given the job of producing a new master analysis sheet each month from a supplied XML file that combines with various columns of our (multiple) sheets. No problems, so far. I have got all of that working the way I want. :-)
My issue is that we also have about 6-8 filters saved with a specific sheet that allow our auditors to focus on specific areas (and as you can understand, our auditors want these to work EXACTLY as they specify).
I have tried using createFilter() but there doesn't appear any way to save multiple filters to that sheet (maybe I am missing something). No joy! :-(
I have tried recording a macro which I could then run to create the filters. No joy here either :-(
Do I have to tell these pesky auditors to create there own filters each month (they do know how, but it's beneath them), or is there a way I can script them up and get them off my back?
Unfortunately (as much as I would like to) I cannot share our sheets or scripts as we have significant IP embedded there.
I would really appreciate some guidance as to how you might approach this (if it is possible).
Kind regards
Ian
If you're indeed talking about the 'Create new filter view', I suggest making an template sheet. So instead of creating a new sheet every month, make one template spreadsheet and add all the filter views your auditors desire. Then copy that spreadsheet, and paste the new data in it.
The correct way to create a filter using Apps Script and the createFilter() is this one:
function setFilters() {
var ss = SpreadsheetApp.getActiveSheet();
var rangeFilter = ss.getRange("INPUT_YOUR_RANGE_HERE");
var filter = rangeFilter1.createFilter();
var filterCriteria = SpreadsheetApp.newFilterCriteria();
filterCriteria.ADD_YOUR_CRITERIA_HERE;
filter.setColumnFilterCriteria(columnPosition, filterCriteria.build());
}
As you can see, you must use build() in order to build the criteria for the filter you have created.
You can also use the Sheets advanced services and create the filters using the Sheets API, something similar to this:
var filterSettings = {
//YOUR FILTER SETTINGS
};
var request = [{
"setBasicFilter": {
"filter": filterSettings
}
}];
And as for calling the Sheets service and applying the above filter, you can use this:
Sheets.Spreadsheets.batchUpdate({'requests': request}, SPREADSHEET_ID);
Reference
Range Class Apps Script createFilter();
Filter Class Apps Script;
Apps Script Google Advanced Services.
Hello :) I wonder if there is a script/Google script that takes several Google Docs Documents with the same table inside,same structure(I mean table with first name,last name,age,classroom,final grade) and puts everything in a Google Spreadsheet table so that each row identify a student to have a collection of all the students in my year and if I modify a Google Document of a student it will modify in the spreadsheet and vice-versa if I modify the data in the speadsheet(like the classroom) it will modify in the Google Doc ? Thank you very much and I know that there is autoCrat but for each student I have a Google Doc file and I would be perfect to have a spreadsheet table.
Edit : I a very sorry if my question doesn't repect your policy I've tried this code :
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
if(body)
{
var numChildren=body.getNumChildren();
for(var i=0;i<numChildren;i++)
{
var child=body.getChild(i);
if(child.getType()==DocumentApp.ElementType.TABLE)
{
var numrows = child.asTable().getNumRows();
for(var j=0;j<numrows;j++)
{
var numcells=child.asTable().getRow(j).getNumCells();
for(var k=0;k<numcells;k++)
{
var celltxt=child.asTable().getCell(j, k).editAsText().getText();
but to export after that in a spreadsheet I am blocked :( if you have an idea
There are 2 roundabouts for this that may work for you:
-If you want a better setup from the start you can do an integration of Google Forms, Google Sites, and Google Sheets.
-If you want something that works with the info you have now, you can create a pivot sheet that pulls data via the function IMPORTHTML https://support.google.com/docs/answer/3093339?hl=en
There are other functions that may be of use: https://support.google.com/docs/table/25273?hl=en&ref_topic=9199554
Ideally if you want to set a whole system, you can directly have a Google Form fed the information into a concrete Google Sheets (and you can leave open the form's option to edit answers) and you can make multiple forms fed the same sheet that create different tabs for each form, and then have a table that combines them all.
Since you can insert Docs, Sheets and Forms into a Google Sites then you can re-plan all this from the start.
Otherwise you can just try the import functions in a pivot sheet.
Column F have a Formula value when I read in script is show #N/A.
Below is a very simple script code, but I'm unable to understand why it is showing #N/A, I didn't implement any trigger.
var spreadsheet =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var values = spreadsheet.getDataRange().getValues();
Logger.log(values[1][0]);
Logger.log(values[1][5]);
https://docs.google.com/spreadsheets/d/18EsMMrC1IbzkZaIb5aIx3OfwvN1VzdmHm5B-YVuCMs4/edit?usp=sharing
How about a following modification?
From :
var values = spreadsheet.getDataRange().getValues();
To :
var values = spreadsheet.getDataRange().getDisplayValues();
The detail information of getDisplayValues() is here.
If I misunderstand your question, I'm sorry.
Edit
When I tried to retrieve the data using Sheet API v4, following error message occurred.
"#N/A (Historical GOOGLEFINANCE data is not available outside of the Google Sheets UI.)"
So I investigated about this error. And I found a following document.
We want to make you aware of a small change to the GOOGLEFINANCE function, which makes it easy to pull current or historical securities information directly into your spreadsheets in Google Sheets. Starting today, it will not be possible to download historical data or access it outside of Sheets using Apps Script or an API. If you have a spreadsheet with historical data generated from the GOOGLEFINANCE function and you try to download it or access it via Apps Script or an API, the corresponding cells will show “#N/A.” You will still be able to view that historical data from within the Sheets application, and you will still be able to download current data and access current data via Apps Script or an API. Please keep this in mind when using the GOOGLEFINANCE function going forward.
Document : https://gsuiteupdates.googleblog.com/2016/09/historical-googlefinance-data-no-longer.html
Updated at July 30, 2022:
At May 18, 2022, I noticed that the values from GOOGLEFINANCE on Spreadsheet can be retrieved using a Google Apps Script.
Testing:
Put the following sample formula into the Spreadsheet.
=GOOGLEFINANCE("NASDAQ:GOOG","price",DATE(2022,5,1),DATE(2022,5,10),"DAILY")
The image of this sample situation is as follows.
When the following sample scripts with Spreadsheet service (SpreadsheetApp) are used,
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
const values = sheet.getDataRange().getDisplayValues(); // or getValues()
console.log(values);
And, when the following sample scripts with Sheets API are used,
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const values = Sheets.Spreadsheets.Values.get(spreadsheetId, "Sheet1").values;
console.log(values);
the following result is obtained.
[
["Date", "Close"],
["2022/05/02 16:00:00", "2343.14"],
["2022/05/03 16:00:00", "2362.59"],
["2022/05/04 16:00:00", "2451.5"],
["2022/05/05 16:00:00", "2334.93"],
["2022/05/06 16:00:00", "2313.2"],
["2022/05/09 16:00:00", "2261.68"]
]
Note:
Unfortunately, I cannot find the change in this specification in the official document. And, I'm not sure whether this is the current specification. So, this situation might be changed in the future update. Please be careful about this.
References:
Report: Obtaining Values from GOOGLEFINANCE using Google Apps Script
Checking Exchange Rate using GOOGLEFINANCE with Google Apps Script
I am not a coder, but I am hacking my way through a Google Apps script to import data from the fitness app Strava to a Google sheet and manipulate that data for analysis. I have managed to use the Strava API and Google sheets API to import the data. However, now, I need to find a way to sort my data so I can analyze it. Since the Strava API appends a new line with each fitness activity, it appears I must duplicate the data (values) into a new sheet. I've tried using formulas to pull the data from the import sheet, but it doesn't seem to work once sorted. Therefore, one solution that comes to mind is to use the spreadsheets.values collection in the Sheets API to add data to a new sheet. THis leads to two questions:
Is there a best practice for filtering dynamic data?
Assuming the approach above is reasonable, what would the code look like? The examples Google gives in the Sheets API documentation do not include Apps Scripts, and I'm not a coder, so I'm looking for help. Here's what I've written thus far. "rangeNamefrom" is the sheet that receives the Strava data."rangeNameto" is the sheet where I want to place the data as values. Any help would be greatly appreciated. Thanks in advance.
/**
* Creates a Sheets API service object and transfers data from one tab to another of the following spreadsheet as values
* https://docs.google.com/spreadsheets/d/10mCWosPmxW71WtuHDtsfpfVU5459NJ24IRbHtxYwoCI/edit#gid=2030256469
*/
function TransferValues() {
var spreadsheetId = '10mCWosPmxW71WtuHDtsfpfVU5459NJ24IRbHtxYwoCI';
var rangeNamefrom = 'ProcessedData!A2:AZ1000';
var rangeNameto = 'ViewTabs!A2:AZ1000';
var values = SpreadsheetApp.values.batchGet(spreadsheetId, rangeNamefrom).values;
if (!values) {
Logger.log('No data found.');
} else {
SpreadsheetApp.values.batchUpdate(spreadsheetId, rangeNameto).values;
}
}
The batchUpdate method is not available with the SpreadsheeetApp service. You need to switch to the advanced Sheets service as described in the documentation.
You'll also have to enable the Google Sheets API in the associated console project.