Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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. But if there is no option.. Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your issue can be solved by using an onOpen(e) trigger and by hosting your python script on Google Cloud.

1. Use the onOpen(e) trigger

The onOpen(e) trigger is used to create the menu MY MENU in your Spreadsheet each time the Spreadsheet opens. 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.

onOpen(e) behavior

The above behavior can be achieved by using this snippet in Apps Script

function onOpen(e) {
  SpreadsheetApp.getUi()
      .createMenu('MY MENU')
      .addItem('TRIGGER THE PYTHON SCRIPT', 'runScript')
      .addToUi();
}

2. Host your Python script on Google Cloud

You should host your Python Script in Google Cloud as a Cloud Function and run the code.

The runScript() is the function triggered by TRIGGER THE PYTHON SCRIPT menu from above and the snippet looks something like this.

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.

Reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...