Adding Buttons To Google Sheets and Set value to Cells on clicking - google-apps-script

I am new to Google Script.
I have a Google Sheet with 5 columns, on each column I need a button (with text 1,2,3,4,5).
And on each button click I need to set text of button to corresponding cell and hide the clicked button.
Is it possible?

You can insert an image that looks like a button. Then attach a script to the image.
INSERT menu
Image
You can insert any image. The image can be edited in the spreadsheet
Image of a Button
Assign a function name to an image:

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.
In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.

Related

Is it possible to insert a Bookmark in Google Docs to a Table Cell/Table/Text via Google Apps Script?

Is it possible to insert a Bookmark at a table cell or text in Google Docs using Google Apps Script by e.g. specifying the table cell? From the documentation I understand that you need the absolute position which is bound to the cursor. What if I want to set Bookmarks at specified tables automatically. Is that not possible? Here the URL of the documentation:
https://developers.google.com/apps-script/reference/document/bookmark
And if so is it possible to link the inserted bookmark with a table cell using Google Apps Script?
To add a bookmark without using cursors, you can do it via Position class. Since getCursor returns Position, we need to find other methods that returns the same, and that is newPosition which only requires the element and offset (if needed). See code below:
Sample:
Script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// find the text element
var textElement = body.findText("<HERE>").getElement();
// create position using the element
var position = doc.newPosition(textElement, 0)
// addBookmark using the created position
doc.addBookmark(position);
}
Output:
Note:
For other objects, it should be doable as long as you can get the element and use it to get their positions.
Reference:
newPosition

Google Apps Script getText + replaceText from text box inside drawing in Google Docs Impossible?

I'm trying to edit an Avery template in google docs and populate it with information form a google sheet Via Google Apps Script.
I already body.replaceText to replace the placeholder text in the doc:
for (var i in data) {
var row = data[i];
var docid = DriveApp.getFileById(templateid).makeCopy().getId();
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
body.replaceText("%NAME%", row[0]);
body.replaceText("%ADD_LN1%", row[1]);
body.replaceText("%ADD_LN2%", row[2]);
The label template is a table with a drawing oval in each segment and I have inserted a text box inside the The problem i'm having that I have a text box inside the oval drawings in the doc (I need the oval drawings to know where the labels will print)
The placeholder text inside the drawing will not change when I run my script, but any test inside the table or on the page normally will change to the Google sheets information.
Here is the label template I am using: Label Page
I have placed the %NAME& tag in the header, on the image and on the image that is formatted to freeze in place on page (Just in case that changes anything!)
Purpose: I have a google sheet populated with customer name address and custom choices (specific safety information to print onto a label)
I then have this script insert the info into the label doc, then i can print it without having to create them from scratch every time manually.
If there isn't a way to get text / replace text that is within drawing-shape-text, is there a way I can use the circular shape as a table of as guidelines so that I can transfer across the data as standard?
If you need any more info please let me know, I'm very green and very confused.
Thank you in advance for anyone taking the time to read through this!
Unfortunately, in the current stage, there are not methods for directly modifying the texts in the drawing in the methods of Google Apps Script.
From user - Tannaike
Google slides has the function I was looking for.

Insert Image by URL Doesn't Work in Google Apps Script

One of the responses in a Google Forms that I created is uploading an image, which gets saved in my Google Drive along with the URL in the linked spreadsheet. In Google slides I have created an Apps Script and successfully able to create slides for each row/entry along with text from that row, from the spreadsheet, but are having difficulty trying to insert an image using by URL. At run time I get the exception thrown "The image at URL ... could not be retrieved. Please make sure the image is valid and publicly accessible." I also get the same error when I manually try to insert the image by URL via the menu bar. All folders and files in my drive are not restricted, so any one on the internet can view the image with this link. And I have tested that out both in my browser and others and it successfully opens the image, but not in Slides.
I must be missing something, but can't figure it out.
Here is some code I am using from the function, but not including the reference to the spreadsheet. Have tried adding '/edit', '/view' to the end of the URL as well, but with same results. Logger does shows the URL is being grabbed from the sheet.
function CreateSlides() {
var deck = SlidesApp.getActivePresentation();
var a = 2; // data begins in second row in spreadsheet
while (sheet.getRange(a,2,1,1).getValue() != "") {
//Insert new slide if not first slide
if (a != 2) {
slide = deck.insertSlide(a-2,SlidesApp.PredefinedLayout.BLANK); //add new slide
} else {
slide = deck.getSlides()[0]; //get first slide
}
// Insert image of painting
Logger.log(sheet.getRange(paintingURLCol + a).getValue());
var picture = slide.insertImage(sheet.getRange(paintingURLCol + a).getValue() + '/view');
// Edit picture size and position
// Increment counter to next row in sheet
a++;
}
}
The URLs logged by Google Form by upload question type can't be used with methods like insertImage(URL) because those URLs aren't supported. Instead you should use:
https://drive.google.com/uc?id=DRIVE_FILE_ID
The above becase the URLs logged to the spreadsheet points to a page with the image embedded not to the actual image file.
Related
Inserting a Google Drive image into a document using Google Apps Script
Display Images from Google Drive folder
How do I script a photo from Google Form upload and set its size to 1 inch for display in a template?
Thanks Rubén. And that's what I actually did and it solved the issue. Here is the sample code that I used for the solution.
var fileURL = sheet.getRange(paintingURLCol + a).getValue();
var fileID = fileURL.substr(fileURL.search("=")+1); //strip off text before id= in the URL
var file = DriveApp.getFileById(fileID);
slide.insertImage(file);

Google Sheets Hide Images When Hiding Rows

I have been trying to figure out a way to hide an image in google sheets when I am hiding rows that include the image.
The image is a button that has a script attached to it, which means that I cannot just use the =IMAGE() formula, and cannot use an image inside of a cell either.
The problem is that when I hide rows the image stays. Is there any way to get around this?
Answer:
Unfortunately, there is no way of doing this.
More Information:
Images in a Google Sheet that are not inserted using the =IMAGE() formula, nor by inserting the image directly in a cell, are represented by an OverGridImage object in Google Apps Script.
As you can see in the documentation for this class, there exists no method which allows you to hide the image, other than deleting it altogether.
The reason that hiding cells/rows/columns does not hide the image either, is because the image is not tied to any indvidual cell, row or column - it is inserted over the grid system of a specific sheet.
A Mix of Both Good and Bad News:
Now, in theory, what you could do instead, is store the information about the image in the script properties, and then delete/insert the image again when you wish to hide it.
Unfortunately, it appears that the .getUrl() method of the aforementioned OverGridImage class is bugged and does not return the URL of the image - this is something that I have checked myself.
In this case, I would suggest going to the issue link for this bug and hit the ☆ next to the issue number in the top left to let Google know that more people need this to be seen to.
I would also suggest filing a Feature Request with Google here, detailing that you would like to see the showing and hiding of overlay images implemented in Google Apps Script. The above link is directly for Apps Script feature requests.
And for future readers: If you are encountering this, and the .getUrl() method has been fixed, then you can use the following functions as a workaround to show and hide images. This uses PropertiesService to save the image data into the script's properties, and then uses them to re-insert the image after deletion.
function hideImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var image = ss.getImages(); // assuming this is the only image
var url = image[0].getUrl();
var col = image[0].getAnchorCell().getColumn();
var row = image[0].getAnchorCell().getRow();
var xOffset = image[0].getAnchorCellXOffset();
var yOffset = image[0].getAnchorCellYOffset();
var details = [url, col, row, xOffset, yOffset];
console.log(details);
PropertiesService.getScriptProperties().setProperty("image", details.toString());
image[0].remove();
}
function showImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var details = PropertiesService.getScriptProperties().getProperty("image").split(",");
// change for your sheet name
ss.getSheetByName("Sheet1")
.insertImage(details[0], details[1], details[2], details[3], details[4])
}
References:
Class OverGridImage | Apps Script | Google Developers
OverTheGrid Image getUrl() seems to not working - Google Issue Tracker
Google Apps Script Feature Request Form - Google Issue Tracker
Class PropertiesService | Apps Script | Google Developers
insertImage(url, column, row, offsetX, offsetY) - Class Spreadsheet | Apps Script

Google Apps Script Text rotation

I found in the UI of Google Spreadsheet the functionality Text Rotation but i found no equal function in google apps script.
So how can i rotate Text with Google apps script?
Regards
Edit: I created a Spreadsheet with the needed rotation as default setting after this a make a copy of this spreadsheet.
I know this is an old ask but incase others are interested...This can be done now. Just add .setTextRotation() to any range selected and it will rotate the text to the desired degree. For example:
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(1,1).setTextRotation(-45);
Documentation: https://developers.google.com/apps-script/reference/spreadsheet/range-list#setTextRotation(Integer)
You may follow the formula given in this thread. Here's a sample code:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var cell = sheet.getRange(1,1);
cell.setValue('=ARRAYFORMULA(CONCATENATE((MID($B2, ROW(INDIRECT("YY1:YY"&LEN($B2))), 1)&CHAR(10))))');
}
In this example, we'll set the value of B2 in A1 in vertical format. Hope this helps.