העתקת פקודות מאקרו לגיליונות אלקטרוניים אחרים

רמת הקוד: בינונית
משך: 30 דקות
סוג הפרויקט: תוסף ל-Google Workspace

מטרות

  • להבין מה הפתרון עושה.
  • הסבר על הפעולות של שירותי Apps Script בתוך הפתרון.
  • מגדירים את הסביבה.
  • מגדירים את הסקריפט.
  • מריצים את הסקריפט.

מידע על הפתרון הזה

העתקה ידנית של מאקרו ב-Google Sheets מגיליון אלקטרוני אחד לגיליון אחר עשויה להיות זמן רב ומועדת לשגיאות. התוסף הזה ל-Google Workspace מעתיק באופן אוטומטי פרויקט סקריפט ומצרף אותו לגיליון אלקטרוני שהמשתמש מציין. הפתרון הזה מתמקד במאקרוסים של Sheets, אבל אפשר להשתמש בו כדי להעתיק ולשתף כל סקריפט שמקושר לקונטיינר.

צילום מסך של התוסף Share Macro ל-Google Workspace

איך זה עובד

הסקריפט מעתיק את פרויקט Apps Script שמקושר לגיליון האלקטרוני המקורי ויוצר עותק כפול של פרויקט Apps Script שמקושר לגיליון האלקטרוני שצוין על ידי המשתמש.

שירותי Apps Script

הפתרון הזה משתמש בשירותים הבאים:

דרישות מוקדמות

כדי להשתמש בדוגמה הזו, צריך את הדרישות המוקדמות הבאות:

הגדרת הסביבה

פותחים את פרויקט Cloud במסוף Google Cloud

אם הוא עדיין לא פתוח, פותחים את פרויקט Cloud שבו רוצים להשתמש לדוגמה הזו:

  1. נכנסים לדף Select a project במסוף Google Cloud.

    בחירת פרויקט ב-Cloud

  2. בוחרים את הפרויקט ב-Google Cloud שבו רוצים להשתמש. לחלופין, לוחצים על Create project (יצירת פרויקט) ופועלים לפי ההוראות במסך. אם יוצרים פרויקט ב-Google Cloud, יכול להיות שתצטרכו להפעיל את החיוב בפרויקט.

הפעלת Google Apps Script API

במדריך למתחילים הזה נעשה שימוש ב-Google Apps Script API.

לפני שמשתמשים ב-Google APIs, צריך להפעיל אותם בפרויקט ב-Google Cloud. אפשר להפעיל ממשק API אחד או יותר בפרויקט אחד ב-Google Cloud.

כדי להשתמש בתוספים של Google Workspace, צריך להגדיר מסך הסכמה. הגדרת מסך ההסכמה ל-OAuth של התוסף קובעת מה Google תציג למשתמשים.

  1. במסוף Google Cloud, נכנסים לתפריט > > Branding.

    כניסה לדף Branding

  2. אם כבר הגדרתם את , תוכלו להגדיר את ההגדרות הבאות של מסך ההסכמה ל-OAuth בקטע מיתוג, קהל וגישה לנתונים. אם מופיעה ההודעה not configured yet, לוחצים על Get Started:
    1. בקטע פרטי האפליקציה, בשדה שם האפליקציה, מזינים שם לאפליקציה.
    2. בקטע כתובת אימייל לתמיכה במשתמשים, בוחרים כתובת אימייל לתמיכה שבה המשתמשים יוכלו לפנות אליכם אם יש להם שאלות לגבי ההסכמה שלהם.
    3. לוחצים על הבא.
    4. בקטע קהל, בוחרים באפשרות פנימי.
    5. לוחצים על הבא.
    6. בקטע פרטים ליצירת קשר, מזינים כתובת אימייל שאליה יישלחו התראות על שינויים בפרויקט.
    7. לוחצים על הבא.
    8. בקטע סיום, קוראים את המדיניות בנושא נתוני משתמשים בשירותי Google API. אם מסכימים, בוחרים באפשרות אני מסכים/ה למדיניות בנושא נתוני משתמשים בשירותי Google API.
    9. לוחצים על המשך.
    10. לוחצים על יצירה.
  3. בשלב הזה, אפשר לדלג על הוספת היקפי הרשאות. בעתיד, כשיוצרים אפליקציה לשימוש מחוץ לארגון ב-Google Workspace, צריך לשנות את סוג המשתמש לחיצוני. לאחר מכן מוסיפים את היקפי ההרשאה הנדרשים לאפליקציה. למידע נוסף, קראו את המדריך המלא בנושא הגדרת הסכמה ל-OAuth.

הגדרת הסקריפט

יצירת פרויקט Apps Script

  1. לוחצים על הלחצן הבא כדי לפתוח את הפרויקט שיתוף מאקרו ב-Apps Script.
    פתיחת הפרויקט
  2. לוחצים על סקירה כללית .
  3. בדף הסקירה הכללית, לוחצים על 'יצירת עותק' הסמל ליצירת עותק.

מעתיקים את מספר הפרויקט ב-Cloud

  1. במסוף Google Cloud, נכנסים לתפריט > IAM & Admin > Settings.

    כניסה לדף IAM & Admin

  2. בשדה Project number, מעתיקים את הערך.

הגדרת הפרויקט ב-Cloud של פרויקט Apps Script

  1. בפרויקט Apps Script שהעתקתם, לוחצים על Project Settings (הגדרות הפרויקט) הסמל של הגדרות הפרויקט.
  2. בקטע פרויקט Google Cloud Platform (GCP), לוחצים על שינוי פרויקט.
  3. בשדה GCP project number, מדביקים את מספר הפרויקט ב-Google Cloud.
  4. לוחצים על Set project.

התקנת פריסה לבדיקה

  1. בפרויקט Apps Script שהעתקתם, לוחצים על Editor (עריכה) .
  2. פותחים את הקובץ UI.gs ולוחצים על הפעלה. כשמוצגת בקשה, מאשרים את הסקריפט.
  3. לוחצים על פריסה > בדיקת הפריסות.
  4. לוחצים על התקנה > סיום.

אחזור הסקריפט של המאקרו ומידע על הגיליון האלקטרוני

  1. פותחים גיליון אלקטרוני ב-Sheets שמכיל מאקרו ויש לכם הרשאה לערוך אותו. כדי להשתמש בגיליון אלקטרוני לדוגמה, יוצרים עותק של הגיליון האלקטרוני Sample macro.
  2. לוחצים על תוספים > Apps Script.
  3. בפרויקט Apps Script, לוחצים על Project settings (הגדרות הפרויקט) הסמל של הגדרות הפרויקט.
  4. מתחת למזהה הסקריפט, לוחצים על העתקה.
  5. שומרים את מזהה הסקריפט לשימוש בשלב מאוחר יותר.
  6. פותחים או יוצרים גיליון אלקטרוני חדש שבו רוצים להוסיף את המאקרו. צריכה להיות לכם הרשאה לערוך את הגיליון האלקטרוני.
  7. מעתיקים את כתובת ה-URL של הגיליון האלקטרוני ומניחים אותה בצד לשימוש בשלב מאוחר יותר.

מריצים את הסקריפט

מוודאים שממשק ה-API של Google Apps Script מופעל בהגדרות של מרכז הבקרה. כדי להריץ את הסקריפט, פועלים לפי השלבים שמפורטים בקטעים הבאים.

העתקת המאקרו

  1. ב-Sheets, בסרגל הצד הימני, פותחים את התוסף Share Macro‏הסמל ליצירת עותק.
  2. בקטע Source macro (מאקרו של מקור), מדביקים את מזהה הסקריפט.
  3. בקטע גיליון אלקטרוני יעד, מדביקים את כתובת ה-URL של הגיליון האלקטרוני.
  4. לוחצים על שיתוף המאקרו.
  5. לוחצים על אישור גישה ומאשרים את התוסף.
  6. חוזרים על שלבים 2 עד 4.

פתיחת המאקרו שהועתק

  1. אם הגיליון האלקטרוני שאליו העתקתם את המאקרו עדיין לא פתוח, פותחים אותו.
  2. לוחצים על תוספים > Apps Script.
  3. אם פרויקט Apps Script שהעתקתם לא מופיע, עליכם לוודא ש-Google Apps Script API מופעל בהגדרות של לוח הבקרה וחוזרים על השלבים שמפורטים בקטע העתקת המאקרו.

בדיקת הקוד

כדי לבדוק את הקוד של Apps Script לפתרון הזה, לוחצים על הצגת קוד המקור בהמשך:

הצגת קוד המקור

Code.gs

solutions/add-on/share-macro/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.devsite.corp.google.com/apps-script/add-ons/share-macro

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Uses Apps Script API to copy source Apps Script project 
 * to destination Google Spreadsheet container.
 * 
 * @param {string} sourceScriptId - Script ID of the source project.
 * @param {string} targetSpreadsheetUrl - URL if the target spreadsheet.
 */
function shareMacro_(sourceScriptId, targetSpreadsheetUrl) {

  // Gets the source project content using the Apps Script API.
  const sourceProject = APPS_SCRIPT_API.get(sourceScriptId);
  const sourceFiles = APPS_SCRIPT_API.getContent(sourceScriptId);

  // Opens the target spreadsheet and gets its ID.
  const parentSSId = SpreadsheetApp.openByUrl(targetSpreadsheetUrl).getId();

  // Creates an Apps Script project that's bound to the target spreadsheet.
  const targetProjectObj = APPS_SCRIPT_API.create(sourceProject.title, parentSSId);

  // Updates the Apps Script project with the source project content.
  APPS_SCRIPT_API.updateContent(targetProjectObj.scriptId, sourceFiles);

}

/**
 * Function that encapsulates Apps Script API project manipulation. 
*/
const APPS_SCRIPT_API = {
  accessToken: ScriptApp.getOAuthToken(),

  /* APPS_SCRIPT_API.get
   * Gets Apps Script source project.
   * @param {string} scriptId - Script ID of the source project.
   * @return {Object} - JSON representation of source project.
   */
  get: function (scriptId) {
    const url = ('https://script.googleapis.com/v1/projects/' + scriptId);
    const options = {
      "method": 'get',
      "headers": {
        "Authorization": "Bearer " + this.accessToken
      },
      "muteHttpExceptions": true,
    };
    const res = UrlFetchApp.fetch(url, options);
    if (res.getResponseCode() == 200) {
      return JSON.parse(res);
    } else {
      console.log('An error occurred gettting the project details');
      console.log(res.getResponseCode());
      console.log(res.getContentText());
      console.log(res);
      return false;
    }
  },

  /* APPS_SCRIPT_API.create
   * Creates new Apps Script project in the target spreadsheet.
   * @param {string} title - Name of Apps Script project.
   * @param {string} parentId - Internal ID of target spreadsheet.
   * @return {Object} - JSON representation completed project creation.
   */
  create: function (title, parentId) {
    const url = 'https://script.googleapis.com/v1/projects';
    const options = {
      "headers": {
        "Authorization": "Bearer " + this.accessToken,
        "Content-Type": "application/json"
      },
      "muteHttpExceptions": true,
      "method": "POST",
      "payload": { "title": title }
    }
    if (parentId) {
      options.payload.parentId = parentId;
    }
    options.payload = JSON.stringify(options.payload);
    let res = UrlFetchApp.fetch(url, options);
    if (res.getResponseCode() == 200) {
      res = JSON.parse(res);
      return res;
    } else {
      console.log("An error occurred while creating the project");
      console.log(res.getResponseCode());
      console.log(res.getContentText());
      console.log(res);
      return false;
    }
  },
   /* APPS_SCRIPT_API.getContent
   * Gets the content of the source Apps Script project.
   * @param {string} scriptId - Script ID of the source project.
   * @return {Object} - JSON representation of Apps Script project content.
   */
   getContent: function (scriptId) {
    const url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content";
    const options = {
      "method": 'get',
      "headers": {
        "Authorization": "Bearer " + this.accessToken
      },
      "muteHttpExceptions": true,
    };
    let res = UrlFetchApp.fetch(url, options);
    if (res.getResponseCode() == 200) {
      res = JSON.parse(res);
      return res['files'];
    } else {
      console.log('An error occurred obtaining the content from the source script');
      console.log(res.getResponseCode());
      console.log(res.getContentText());
      console.log(res);
      return false;
    }
  },

  /* APPS_SCRIPT_API.updateContent
   * Updates (copies) content from source to target Apps Script project.
   * @param {string} scriptId - Script ID of the source project.
   * @param {Object} files - JSON representation of Apps Script project content.
   * @return {boolean} - Result status of the function.
   */
  updateContent: function (scriptId, files) {
    const url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content";
    const options = {
      "method": 'put',
      "headers": {
        "Authorization": "Bearer " + this.accessToken
      },
      "contentType": "application/json",
      "payload": JSON.stringify({ "files": files }),
      "muteHttpExceptions": true,
    };
    let res = UrlFetchApp.fetch(url, options);
    if (res.getResponseCode() == 200) {
      return true;
    } else {
      console.log(`An error occurred updating content of script ${scriptId}`);
      console.log(res.getResponseCode());
      console.log(res.getContentText());
      console.log(res);
      return false;
    }
  }
}

UI.gs

solutions/add-on/share-macro/UI.js
/**
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Change application logo here (and in manifest) as desired.
const ADDON_LOGO = 'https://www.gstatic.com/images/branding/product/2x/apps_script_48dp.png';

/**
 * Callback function for rendering the main card.
 * @return {CardService.Card} The card to show the user.
 */
function onHomepage(e) {
  return createSelectionCard(e);
}

/**
 * Builds the primary card interface used to collect user inputs.
 * 
 * @param {Object} e - Add-on event object.
 * @param {string} sourceScriptId - Script ID of the source project.
 * @param {string} targetSpreadsheetUrl - URL of the target spreadsheet.
 * @param {string[]} errors - Array of error messages. 
 * 
 * @return {CardService.Card} The card to show to the user for inputs.
 */
function createSelectionCard(e, sourceScriptId, targetSpreadsheetUrl, errors) {

  // Configures card header.
  let cardHeader = CardService.newCardHeader()
    .setTitle('Share macros with other spreadheets!')
    .setImageUrl(ADDON_LOGO)
    .setImageStyle(CardService.ImageStyle.SQUARE);

  // If form errors exist, configures section with error messages.
  let showErrors = false;

  if (errors && errors.length) {
    showErrors = true;
    let msg = errors.reduce((str, err) => `${str}${err}<br>`, '');
    msg = `<b>Form submission errors:</b><br><font color="#ba0000">${msg}</font>`;

    // Builds error message section.
    sectionErrors = CardService.newCardSection()
      .addWidget(CardService.newDecoratedText()
        .setText(msg)
        .setWrapText(true));
  }

  // Configures source project section.
  let sectionSource = CardService.newCardSection()
    .addWidget(CardService.newDecoratedText()
      .setText('<b>Source macro</b><br>The Apps Script project to copy'))

    .addWidget(CardService.newTextInput()
      .setFieldName('sourceScriptId')
      .setValue(sourceScriptId || '')
      .setTitle('Script ID of the source macro')
      .setHint('You must have at least edit permission for the source spreadsheet to access its script project'))

    .addWidget(CardService.newTextButton()
      .setText('Find the script ID')
      .setOpenLink(CardService.newOpenLink()
        .setUrl('https://developers.google.com/apps-script/api/samples/execute')
        .setOpenAs(CardService.OpenAs.FULL_SIZE)
        .setOnClose(CardService.OnClose.NOTHING)));

  // Configures target spreadsheet section.
  let sectionTarget = CardService.newCardSection()
    .addWidget(CardService.newDecoratedText()
      .setText('<b>Target spreadsheet</b>'))

    .addWidget(CardService.newTextInput()
      .setFieldName('targetSpreadsheetUrl')
      .setValue(targetSpreadsheetUrl || '')
      .setHint('You must have at least edit permission for the target spreadsheet')
      .setTitle('Target spreadsheet URL'));

  // Configures help section.
  let sectionHelp = CardService.newCardSection()
    .addWidget(CardService.newDecoratedText()
      .setText('<b><font color=#c80000>NOTE: </font></b>' +
        'The Apps Script API must be turned on.')
      .setWrapText(true))

    .addWidget(CardService.newTextButton()
      .setText('Turn on Apps Script API')
      .setOpenLink(CardService.newOpenLink()
        .setUrl('https://script.google.com/home/usersettings')
        .setOpenAs(CardService.OpenAs.FULL_SIZE)
        .setOnClose(CardService.OnClose.NOTHING)));

  // Configures card footer with action to copy the macro.
  var cardFooter = CardService.newFixedFooter()
    .setPrimaryButton(CardService.newTextButton()
      .setText('Share macro')
      .setOnClickAction(CardService.newAction()
        .setFunctionName('onClickFunction_')));

  // Begins building the card.
  let builder = CardService.newCardBuilder()
    .setHeader(cardHeader);

  // Adds error section if applicable.
  if (showErrors) {
    builder.addSection(sectionErrors)
  }

  // Adds final sections & footer.
  builder
    .addSection(sectionSource)
    .addSection(sectionTarget)
    .addSection(sectionHelp)
    .setFixedFooter(cardFooter);

  return builder.build();
}

/**
 * Action handler that validates user inputs and calls shareMacro_
 * function to copy Apps Script project to target spreadsheet.
 * 
 * @param {Object} e - Add-on event object.
 * 
 * @return {CardService.Card} Responds with either a success or error card.
 */
function onClickFunction_(e) {

  const sourceScriptId = e.formInput.sourceScriptId;
  const targetSpreadsheetUrl = e.formInput.targetSpreadsheetUrl;

  // Validates inputs for errors.
  const errors = [];

  // Pushes an error message if the Script ID parameter is missing.
  if (!sourceScriptId) {
    errors.push('Missing script ID');
  } else {

    // Gets the Apps Script project if the Script ID parameter is valid.
    const sourceProject = APPS_SCRIPT_API.get(sourceScriptId);
    if (!sourceProject) {
      // Pushes an error message if the Script ID parameter isn't valid.
      errors.push('Invalid script ID');
    }
  }

  // Pushes an error message if the spreadsheet URL is missing.
  if (!targetSpreadsheetUrl) {
    errors.push('Missing Spreadsheet URL');
  } else
    try {
      // Tests for valid spreadsheet URL to get the spreadsheet ID.
      const ssId = SpreadsheetApp.openByUrl(targetSpreadsheetUrl).getId();
    } catch (err) {
      // Pushes an error message if the spreadsheet URL parameter isn't valid.
      errors.push('Invalid spreadsheet URL');
    }

  if (errors && errors.length) {
    // Redisplays form if inputs are missing or invalid.
    return createSelectionCard(e, sourceScriptId, targetSpreadsheetUrl, errors);

  } else {
    // Calls shareMacro function to copy the project.
    shareMacro_(sourceScriptId, targetSpreadsheetUrl);

    // Creates a success card to display to users.
    return buildSuccessCard(e, targetSpreadsheetUrl);
  }
}

/**
 * Builds success card to inform user & let them open the spreadsheet.
 * 
 * @param {Object} e - Add-on event object.
 * @param {string} targetSpreadsheetUrl - URL of the target spreadsheet.
 * 
 * @return {CardService.Card} Returns success card.
 */function buildSuccessCard(e, targetSpreadsheetUrl) {

  // Configures card header.
  let cardHeader = CardService.newCardHeader()
    .setTitle('Share macros with other spreadsheets!')
    .setImageUrl(ADDON_LOGO)
    .setImageStyle(CardService.ImageStyle.SQUARE);

  // Configures card body section with success message and open button.
  let sectionBody1 = CardService.newCardSection()
    .addWidget(CardService.newTextParagraph()
      .setText('Sharing process is complete!'))
    .addWidget(CardService.newTextButton()
      .setText('Open spreadsheet')
      .setOpenLink(CardService.newOpenLink()
        .setUrl(targetSpreadsheetUrl)
        .setOpenAs(CardService.OpenAs.FULL_SIZE)
        .setOnClose(CardService.OnClose.RELOAD_ADD_ON)));
  let sectionBody2 = CardService.newCardSection()
    .addWidget(CardService.newTextParagraph()
      .setText('If you don\'t see the copied project in your target spreadsheet,' +
       ' make sure you turned on the Apps Script API in the Apps Script dashboard.'))
    .addWidget(CardService.newTextButton()
      .setText("Check API")
      .setOpenLink(CardService.newOpenLink()
        .setUrl('https://script.google.com/home/usersettings')
        .setOpenAs(CardService.OpenAs.FULL_SIZE)
        .setOnClose(CardService.OnClose.RELOAD_ADD_ON)));

  // Configures the card footer with action to start new process.
  let cardFooter = CardService.newFixedFooter()
    .setPrimaryButton(CardService.newTextButton()
      .setText('Share another')
      .setOnClickAction(CardService.newAction()
        .setFunctionName('onHomepage')));

  return builder = CardService.newCardBuilder()
    .setHeader(cardHeader)
    .addSection(sectionBody1)
    .addSection(sectionBody2)
    .setFixedFooter(cardFooter)
    .build();
 }

appsscript.json

solutions/add-on/share-macro/appsscript.json
{
  "timeZone": "America/Los_Angeles",
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/drive.readonly",
    "https://www.googleapis.com/auth/script.projects"
  ],
    "urlFetchWhitelist": [
    "https://script.googleapis.com/"
  ],
  "addOns": {
    "common": {
      "name": "Share Macro",
      "logoUrl": "https://www.gstatic.com/images/branding/product/2x/apps_script_48dp.png",
      "layoutProperties": {
        "primaryColor": "#188038",
        "secondaryColor": "#34a853"
      },
      "homepageTrigger": {
        "runFunction": "onHomepage"
      }
    },
    "sheets": {}
  }
}

תורמים

Google שומרת על הדוגמה הזו בעזרת מומחי הפיתוח של Google.

השלבים הבאים