[英]Is possible to make a macro in google spreadsheet to execute a python code?
Personally i feel more confortable making a script in python and there are more libraries to use than a macro.就我个人而言,我觉得在 python 中制作脚本更舒服,并且比宏有更多的库可供使用。 But if there is no option.. Thank you in advance.
但如果没有选择.. 提前谢谢你。
Your issue can be solved by using an onOpen(e)
trigger and by hosting your python script
on Google Cloud.您的问题可以通过使用
onOpen(e)
触发器和在 Google Cloud 上托管您的python script
来解决。
1. Use the onOpen(e)
trigger 1. 使用
onOpen(e)
触发器
The onOpen(e)
trigger is used to create the menu MY MENU
in your Spreadsheet each time the Spreadsheet opens.每次电子表格打开时,
onOpen(e)
触发器用于在电子表格中创建菜单MY MENU
。 Moreover, the submenu item TRIGGER THE PYTHON SCRIPT
will have the function runScript()
associated with it and each time you click it, that function will be run.此外,子菜单项
TRIGGER THE PYTHON SCRIPT
将具有与之关联的函数runScript()
,每次单击它时,该函数都会运行。
The above behavior can be achieved by using this snippet in Apps Script可以通过在 Apps 脚本中使用此代码段来实现上述行为
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('MY MENU')
.addItem('TRIGGER THE PYTHON SCRIPT', 'runScript')
.addToUi();
}
2. Host your Python script on Google Cloud 2. 在 Google Cloud 上托管您的 Python 脚本
You should host your Python Script in Google Cloud as a Cloud Function
and run the code.您应该将 Python 脚本作为
Cloud Function
托管在 GCP 中并运行代码。
The runScript()
is the function triggered by TRIGGER THE PYTHON SCRIPT
menu from above and the snippet looks something like this. runScript()
是由上面的TRIGGER THE PYTHON SCRIPT
菜单触发的函数,代码片段看起来像这样。
function runScript() {
var params = {
'method': 'post',
'headers': {
'contentType': 'application/json',
'payload': '{"name":"Name"}'
}
};
var pyScript = UrlFetchApp.fetch('https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME', params);
}
Note: You might have to change the params
based on your script and your desired actions.注意:您可能需要根据脚本和所需的操作更改
params
。
Reference参考
I guess you could run a script yourselves and communicate with the spreadsheet through the API, but as far as I know, you have to use Apps Script to run scripts in the spreadsheet.我想您可以自己运行脚本并通过 API 与电子表格进行通信,但据我所知,您必须使用 Apps 脚本来运行电子表格中的脚本。
Google Sheets API Python quickstart Google Sheets API Python 快速入门
Google Apps Script Google Apps 脚本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.