I am looking to setup a macro in Google Sheets and I am having issues. Below is my script:
function clearRange() {
//replace 'Sheet1'
var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet1.getRange('D3:D46').clearContent();
}
Below is the error I am getting:
TypeError: Cannot call method "getRange" of null. (line 4, file
"Code")
Can any review this and let me know what I am not seeing here.
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
found here
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getSheetByName(String)
Related
OS: Windows 11
Python 3.11, using VS Code
So, I want to use a python script to autofill a bunch of cells in a google spreadsheet, and I was using the guide at https://www.makeuseof.com/tag/read-write-google-sheets-python/. My code to access the spreadsheet and make sure I can write is as follows:
# for writing to google sheets, from https://www.makeuseof.com/tag/read-write-google-sheets-python/
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import json
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name("[filename].json", scopes)
file = gspread.authorize(credentials)
sheet = file.open("[spreadsheetName]")
sheet = sheet.testSheet
So, I run the code, and get the following error:
Traceback (most recent call last):
File "[pythonScriptPath]", line 15, in
sheet = file.open("[spreadsheetName]")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "[anotherPath]", line 160, in open
raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound
Now, I've googled this error and one possible cause was that I didn't share the spreadsheet with the email in the json file. However, I shared it with the email beforehand (ends in iam.gserviceaccount.com) and set it as editor, and even after double-checking and running the script again I'm still getting the error. Could anyone tell me what I'm missing here, please? And the json file and the script are in the same folder.
EDIT: Solved, by instead changing up how I did things and instead using something I found from the gspread documentation (WORKSHEET_NAME is a constant I defined elsewhere in the code, the caps-in-brackets are just the relevant string that I've removed for anonymization):
credentials = gspread.service_account(filename=r'[JSON_FILE_PATH]')
spreadsheet = credentials.open_by_url('[GOOGLE_SHEET_URL]')
worksheet = spreadsheet.worksheet(WORKSHEET_NAME)
The issue is that your service account dosent have access to the file.
The fastest way to fix it is to open the service account json file and find the service account email address its the only one with a # in it
now go to google drive and share the file with the service account like you would any other user
option number two requires that you have a goggle workspace domain and can configure domain wide deligation
I have a Bokeh directory format like below.
BTSapp.py is my equivalent of 'main.py'
In data folder, I have 1 input (excel) file and 1 output (excel) file. I wrote a script to transform the data from the input file and write it to the output file. I would like to create a bokeh button, which when the end users click they can download the output file.
Can someone please help me? I found this question also on stackoverflow: send file from server to client on bokeh but I couldn't make it work in my case. I kept getting syntax error for JScode_xhr.
Thank you in advance.
I tried myself and below is the correct code. It will also fix the issue of double alert and of the generation of 2 excel files after the js code is activated.
Note: this is an adjusted version from this post
JScode_fetch = """
var filename = 'my_BSS_result.xlsx';
fetch('/app/static/output.xlsx', {cache: "no-store"}).then(response => response.blob())
.then(blob => {
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = filename;
link.target = "_blank";
link.style.visibility = 'hidden';
link.dispatchEvent(new MouseEvent('click'))
URL.revokeObjectURL(url);
}
return response.text();
});
"""
I've got an ajax call to a flask route. This ajax call is inside an onlick function of a button (because I have to send some preprocessed data). In the python code,I create a xlsx spreadhseet with 2 tabs and save the file in the server. Then I am trying to download it in the client but without success. No errors, and the response is 200 OK, but the file is not downloaded.
This is my python code:
#app.route('/download_file', methods=['GET', 'POST'])
def download_file():
v1 = request.json['v1']
v2 = request.json['v2']
v1_df = pd.DataFrame(v1, columns=V1_HEADERS)
v2_df = pd.DataFrame(v2, columns=V2_HEADERS)
final_excel = f'resources/final_excel.xlsx'
writer = pd.ExcelWriter(final_excel, engine='xlsxwriter')
v1_df.to_excel(writer, sheet_name='V1', index=False)
v2_df.to_excel(writer, sheet_name='V2', index=False)
writer.save()
return send_file(final_excel, as_attachment=True, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
I also tried send_directory without success.
What am I doing wrong? I'm a little desperate.
Thank you very much in advance.
It seems to me as though you may not be handling the returned file in your Ajax callback correctly. Since this is an Ajax call it will be returned to the relevant callback for you to handle.
So in your .JS code like below handle it as you wish, e.g.
success:function(callback){
var temp = 'file-> ' + callback;
$(doc).text(temp)
}
This may also help - Download a file
it seems that I can't update the sheet (worksheet) name,
what to do?
sh = gc.open('My worksheet')
worksheet = sh.get_worksheet(0)
worksheet.update_title = 'my sheet'
Please take a look at the documentation. You can see that update_title is supposed to be a function call which you call as shown below.
worksheet.update_title('my sheet')
I have a python code which uses drive and sheet api to list the files inside of a folder. I have multiple google sheets inside this folder and some of them have spaces in between texts, like the one given in the image. I wanted to change the text wrap to overflow for all the cells i.e sheet object in python using google sheet api. I can see there is a way (wrap_strategy) to set it to overflow_cell, but I don't know how to use it. Can anyone please help in this case?
I can see the documentation in apps script but not using python.
def process_file(file):
file["name"] = file["name"] + '.' + file["id"] #prefix the file name
print(file["name"])
sheet = open_sheet(file['id'])
if sheet is None:
print("Unable to open sheet: " + file['id'])
return
The actual result would format all google sheets inside this folder with text formatting as overflow for all the cells
You want to set the wrap strategy of a sheet on Spreadsheet.
You want to set the wrap strategy of all cells of the sheet as "overflow".
You want to achieve this using gspread.
From your question and tag, I understood like above. If my understanding is correct, how about this sample script?
In this sample script, it supposes that the wrap strategy of "overflow" is set to all cells of "Sheet1". When batch_update() is used at gspread, the request body is required to be created.
Sample script:
spreadsheetId = "###" # Please set this
sheetName = "Sheet1" # Please set this
client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(spreadsheetId)
sheetId = ss.worksheet(sheetName)._properties['sheetId']
body = {
"requests": [
{
"updateCells": {
"range": {
"sheetId": sheetId,
"startRowIndex": 0,
"startColumnIndex": 0
},
"rows": [
{
"values": [
{
"userEnteredFormat": {
"wrapStrategy": "OVERFLOW_CELL"
}
}
]
}
],
"fields": "userEnteredFormat.wrapStrategy"
}
}
]
}
res = spreadsheet.batch_update(body)
Note:
This sample script supposes that you have already been able to read and write the Spreadsheet using Sheets API.
Unfortunately, I couldn't understand about your script. I'm sorry for this situation.
References:
RepeatCellRequest
WrapStrategy
batch_update(body)
If I misunderstood your question and this was not the result you want, I apologize.
Why not use gspread formatting, it is a simple command:
from gspread_formatting import *
worksheet.format("A1:D10", {"wrapStrategy": "OVERFLOW_CELL"})
In my case I was looking how to set it to WRAP because it was overflow by default...