简体   繁体   中英

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.

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) 行为

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

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.

Google Sheets API Python quickstart
Google Apps Script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM