เริ่มต้นใช้งาน Google Apps Script

สร้าง Google Apps Script ที่ส่งคำขอไปยัง Google Sheets API

บทแนะนำแบบย่อจะอธิบายวิธีตั้งค่าและเรียกใช้แอปที่เรียกใช้ Google Workspace API คู่มือเริ่มต้นฉบับย่อนี้ใช้แนวทางการตรวจสอบสิทธิ์แบบง่ายที่เหมาะกับสภาพแวดล้อมการทดสอบ สําหรับสภาพแวดล้อมเวอร์ชันที่ใช้งานจริง เราขอแนะนําให้ดูข้อมูลเกี่ยวกับการตรวจสอบสิทธิ์และการให้สิทธิ์ก่อนเลือกข้อมูลเข้าสู่ระบบที่เหมาะสมสําหรับแอป

ใน Apps Script ข้อมูลเริ่มต้นใช้งาน Google Workspace ใช้บริการขั้นสูงของ Google เพื่อเรียกใช้ Google Workspace API และจัดการรายละเอียดบางอย่างของการตรวจสอบสิทธิ์และขั้นตอนการให้สิทธิ์

วัตถุประสงค์

  • กำหนดค่าสภาพแวดล้อม
  • สร้างและกําหนดค่าสคริปต์
  • เรียกใช้สคริปต์

ข้อกำหนดเบื้องต้น

  • บัญชี Google
  • การเข้าถึง Google ไดรฟ์

สร้างสคริปต์

  1. สร้างสคริปต์ใหม่โดยไปที่ script.google.com/create
  2. แทนที่เนื้อหาของตัวแก้ไขสคริปต์ด้วยโค้ดต่อไปนี้

sheets/quickstart/quickstart.gs
/**
 * Creates a Sheets API service object and prints the names and majors of
 * students in a sample spreadsheet:
 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
 */
function logNamesAndMajors() {
  const spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
  const rangeName = 'Class Data!A2:E';
  try {
    // Get the values from the spreadsheet using spreadsheetId and range.
    const values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
    //  Print the values from spreadsheet if values are available.
    if (!values) {
      console.log('No data found.');
      return;
    }
    console.log('Name, Major:');
    for (const row in values) {
      // Print columns A and E, which correspond to indices 0 and 4.
      console.log(' - %s, %s', values[row][0], values[row][4]);
    }
  } catch (err) {
    // TODO (developer) - Handle Values.get() exception from Sheet API
    console.log(err.message);
  }
}

  1. คลิกบันทึก
  2. คลิกโปรเจ็กต์ที่ไม่มีชื่อ แล้วพิมพ์เริ่มต้นใช้งานอย่างรวดเร็ว แล้วคลิกเปลี่ยนชื่อ

กำหนดค่าสคริปต์

เปิดใช้ Google Sheets API

เปิดโปรเจ็กต์ Apps Script

  1. คลิกตัดต่อวิดีโอ
  2. คลิกเพิ่มบริการข้างบริการ
  3. เลือก Sheets API แล้วคลิกเพิ่ม

เรียกใช้ตัวอย่าง

คลิกเรียกใช้ในเครื่องมือแก้ไข Apps Script

เมื่อเรียกใช้ตัวอย่างเป็นครั้งแรก ระบบจะแจ้งให้คุณให้สิทธิ์เข้าถึงโดยทำดังนี้

  1. คลิกตรวจสอบสิทธิ์
  2. เลือกบัญชี
  3. คลิกอนุญาต

บันทึกการเรียกใช้สคริปต์จะปรากฏที่ด้านล่างของหน้าต่าง

ขั้นตอนถัดไป