อัปเดตสเปรดชีต

นอกจากข้อมูลค่าที่อยู่ในเซลล์แล้ว สเปรดชีตยังมีข้อมูลประเภทอื่นๆ อีกมากมาย เช่น

  • ขนาด
  • รูปแบบเซลล์และเส้นขอบ
  • ช่วงที่ตั้งชื่อแล้ว
  • ช่วงที่ป้องกันไว้
  • การจัดรูปแบบตามเงื่อนไข

ซึ่งก็คือข้อมูลหลากหลายประเภทที่ควบคุมลักษณะที่ปรากฏและการทำงานของสเปรดชีต เมธอด spreadsheets.batchUpdate ช่วยให้คุณอัปเดตรายละเอียดสเปรดชีตเหล่านี้ได้ การเปลี่ยนแปลงจะได้รับการจัดกลุ่มเป็นกลุ่มๆ เพื่อให้เมื่อคำขอหนึ่งไม่สำเร็จ จะไม่มีการเขียนการเปลี่ยนแปลงอื่นๆ (อาจต้องอาศัยการดำเนินการ)

หน้านี้จะอธิบายพื้นฐานของการใช้เมธอด spreadsheets.batchUpdate หากต้องการอ่านและเขียนข้อมูลค่าเซลล์ คุณจะใช้ทรัพยากร spreadsheets.values ที่อธิบายไว้ในหัวข้ออ่านและเขียนค่าเซลล์ได้ด้วย

หมวดหมู่ของการดำเนินการ

การดำเนินการเฉพาะที่ spreadsheets.batchUpdate รองรับสามารถจัดกลุ่มเป็นหมวดหมู่กว้างๆ ต่อไปนี้

หมวดหมู่ คำอธิบาย
เพิ่ม (และทำซ้ำ)เพิ่มออบเจ็กต์ใหม่ (บางครั้งอาจอิงตามรายการเก่า เช่น คำขอที่ซ้ำกัน)
อัปเดต (และตั้งค่า)อัปเดตพร็อพเพอร์ตี้บางอย่างของออบเจ็กต์ โดยปกติแล้วจะปล่อยพร็อพเพอร์ตี้เก่าไว้ตามเดิม (ในขณะที่คำขอ "ตั้งค่า" จะเขียนทับข้อมูลก่อนหน้านี้)
ลบนำวัตถุออก

หมวดหมู่เหล่านี้จะใช้ในส่วนถัดไปเพื่ออธิบายพฤติกรรมของการดำเนินการที่เฉพาะเจาะจง

การดำเนินการอัปเดตเป็นกลุ่ม

เมธอด spreadsheets.batchUpdate ทำงานโดยนำออบเจ็กต์คำขออย่างน้อย 1 รายการ โดยแต่ละรายการจะระบุคำขอประเภทเดียวเพื่อดำเนินการ คำขอมีหลายประเภท ต่อไปนี้เป็นรายละเอียดเกี่ยวกับประเภทคำขอ ที่จัดกลุ่มตามหมวดหมู่ต่างๆ

ออบเจ็กต์ เพิ่ม / ทำซ้ำ อัปเดต / ตั้งค่า ลบ
พร็อพเพอร์ตี้ของสเปรดชีต UpdateSpreadsheetPropertiesRequest
ชีต AddSheetRequest
DuplicateSheetRequest
UpdateSheetPropertiesRequest DeleteSheetRequest
มิติข้อมูล (รวมถึงช่วงมิติข้อมูล) InsertDimensionRequest
AppendDimensionRequest
UpdateDimensionPropertiesRequest
MoveDimensionRequest
AutoResizeDimensionsRequest
DeleteDimensionRequest
เซลล์ (รวมถึงค่า รูปแบบ การตรวจสอบข้อมูล ฯลฯ) RepeatCellRequest
UpdateCellsRequest
AppendCellsRequest
ช่วงที่ตั้งชื่อแล้ว AddNamedRangeRequest UpdateNamedRangeRequest DeleteNamedRangeRequest
พรมแดน UpdateBordersRequest
ตัวกรอง (รวมถึงมุมมองตัวกรองและตัวกรองพื้นฐาน) AddFilterViewRequest
DuplicateFilterViewRequest
UpdateFilterViewRequest
SetBasicFilterRequest
ClearBasicFilterRequest
การตรวจสอบข้อมูล SetDataValidationRequest
กฎการจัดรูปแบบตามเงื่อนไข AddConditionalFormatRuleRequest UpdateConditionalFormatRuleRequest DeleteConditionalFormatRuleRequest
ช่วงที่ป้องกันไว้ AddProtectedRangeRequest UpdateProtectedRangeRequest DeleteProtectedRangeRequest
ออบเจ็กต์ที่ฝัง (รวมถึงแผนภูมิ) AddChartRequest UpdateChartSpecRequest
UpdateEmbeddedObjectPositionRequest
DeleteEmbeddedObjectRequest
รวม MergeCellsRequest UnmergeCellsRequest

นอกจากนี้ยังมีคำขออื่นๆ ที่เลียนแบบการดำเนินการของผู้ใช้เพื่อบิดเบือนข้อมูลอีกด้วย ดังนี้

ข้อจำกัด

หากต้องการดูข้อมูลเพิ่มเติมเกี่ยวกับขีดจำกัดของเซลล์และแถวใน Google ชีต โปรดดูที่หัวข้อไฟล์ที่เก็บไว้ใน Google ไดรฟ์ได้

มาสก์สนาม

คำขอ "อัปเดต" หลายรายการต้องใช้มาสก์ของช่องข้อมูล ซึ่งเป็นรายการช่องที่คั่นด้วยเครื่องหมายจุลภาคเพื่ออัปเดตเฉพาะบางช่องในออบเจ็กต์ โดยที่ไม่เปลี่ยนแปลงช่องอื่นๆ ระบบจะดำเนินการมาสก์ของช่อง * เหมือนเป็นไวลด์การ์ดและย่อไว้ในการระบุทุกช่องในข้อความ (ซึ่งหมายความว่าช่องอาจเปลี่ยนกลับไปเป็นสถานะเริ่มต้นหากคุณไม่ได้ระบุค่าไว้ในคำขอ) ดูข้อมูลเพิ่มเติมเกี่ยวกับมาสก์ของช่องได้ที่ใช้มาสก์ของช่อง

ตัวอย่างต่อไปนี้ใช้ UpdateSpreadsheetPropertiesRequest เพื่ออัปเดตเฉพาะชื่อสเปรดชีต

คำขอ

POST .../v4/spreadsheets/spreadsheetId:batchUpdate

เนื้อหาของคำขอ:

{
  "requests": [{
      "updateSpreadsheetProperties": {
          "properties": {"title": "TITLE"},
          "fields": "title"
      }
  }]
}

แทนที่ TITLE ด้วยชื่อใหม่ของสเปรดชีต

การตอบกลับ

เมื่ออัปเดตสเปรดชีต คำขอบางประเภทอาจแสดงการตอบกลับ คำตอบเหล่านี้จะแสดงในอาร์เรย์ โดยแต่ละการตอบกลับใช้ดัชนีเดียวกับคำขอที่เกี่ยวข้อง คำขอบางรายการไม่มีการตอบกลับ และคำขอเหล่านั้นไม่มีข้อมูล

โดยปกติแล้ว คำขอ "เพิ่ม" จะมีการตอบกลับที่แสดงข้อมูล เช่น รหัสของออบเจ็กต์ที่เพิ่ม ดูรายการคำตอบที่รองรับได้ที่คำตอบ

ตัวอย่าง

ตัวอย่างโค้ดต่อไปนี้ดำเนินการเหล่านี้

  1. อัปเดตชื่อของสเปรดชีตโดยใช้ตัวแปร title
  2. ค้นหาและแทนที่ค่าเซลล์ในสเปรดชีตโดยใช้ตัวแปร find และ replacement

Apps Script

sheets/api/spreadsheet_snippets.gs
/**
 * Updates the specified sheet using advanced sheet services
 * @param {string} spreadsheetId id of the spreadsheet to be updated
 * @param {string} title name of the sheet in the spreadsheet to be updated
 * @param {string} find string to be replaced
 * @param {string} replacement the string to replace the old data
 * @returns {*} the updated spreadsheet
 */
Snippets.prototype.batchUpdate = (spreadsheetId, title,
  find, replacement) => {
  // This code uses the Sheets Advanced Service, but for most use cases
  // the built-in method SpreadsheetApp.getActiveSpreadsheet()
  //     .getRange(range).setValues(values) is more appropriate.

  try {
    // Change the spreadsheet's title.
    let updateSpreadsheetPropertiesRequest =
      Sheets.newUpdateSpreadsheetPropertiesRequest();
    updateSpreadsheetPropertiesRequest.properties =
      Sheets.newSpreadsheetProperties();
    updateSpreadsheetPropertiesRequest.properties.title = title;
    updateSpreadsheetPropertiesRequest.fields = 'title';

    // Find and replace text.
    let findReplaceRequest = Sheets.newFindReplaceRequest();
    findReplaceRequest.find = find;
    findReplaceRequest.replacement = replacement;
    findReplaceRequest.allSheets = true;

    let requests = [Sheets.newRequest(), Sheets.newRequest()];
    requests[0].updateSpreadsheetProperties =
      updateSpreadsheetPropertiesRequest;
    requests[1].findReplace = findReplaceRequest;

    let batchUpdateRequest = Sheets.newBatchUpdateSpreadsheetRequest();
    batchUpdateRequest.requests = requests;

    // Add additional requests (operations)
    const result =
      Sheets.Spreadsheets.batchUpdate(batchUpdateRequest, spreadsheetId);
    return result;
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', err.message);
  }
};

Java

sheets/snippets/src/main/java/BatchUpdate.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse;
import com.google.api.services.sheets.v4.model.FindReplaceRequest;
import com.google.api.services.sheets.v4.model.FindReplaceResponse;
import com.google.api.services.sheets.v4.model.Request;
import com.google.api.services.sheets.v4.model.SpreadsheetProperties;
import com.google.api.services.sheets.v4.model.UpdateSpreadsheetPropertiesRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/* Class to demonstrate the use of Spreadsheet Batch Update API */
public class BatchUpdate {
  /**
   * Updates spreadsheet's title and cell values.
   *
   * @param spreadsheetId - Id of the spreadsheet.
   * @param title         - New title of the spreadsheet.
   * @param find          - Find cell values
   * @param replacement   - Replaced cell values
   * @return response metadata
   * @throws IOException - if credentials file not found.
   */
  public static BatchUpdateSpreadsheetResponse batchUpdate(String spreadsheetId,
                                                           String title,
                                                           String find,
                                                           String replacement)
      throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Create the sheets API client
    Sheets service = new Sheets.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Sheets samples")
        .build();

    List<Request> requests = new ArrayList<>();
    BatchUpdateSpreadsheetResponse response = null;
    try {
      // Change the spreadsheet's title.
      requests.add(new Request()
          .setUpdateSpreadsheetProperties(new UpdateSpreadsheetPropertiesRequest()
              .setProperties(new SpreadsheetProperties()
                  .setTitle(title))
              .setFields("title")));
      // Find and replace text.
      requests.add(new Request()
          .setFindReplace(new FindReplaceRequest()
              .setFind(find)
              .setReplacement(replacement)
              .setAllSheets(true)));

      BatchUpdateSpreadsheetRequest body =
          new BatchUpdateSpreadsheetRequest().setRequests(requests);
      response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
      FindReplaceResponse findReplaceResponse = response.getReplies().get(1).getFindReplace();

      System.out.printf("%d replacements made.", findReplaceResponse.getOccurrencesChanged());
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 404) {
        System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId);
      } else {
        throw e;
      }
    }
    return response;
  }
}

JavaScript

sheets/snippets/sheets_batch_update.js
function batchUpdate(spreadsheetId, title, find, replacement, callback) {
  const requests = [];
  // Change the spreadsheet's title.
  requests.push({
    updateSpreadsheetProperties: {
      properties: {
        title: title,
      },
      fields: 'title',
    },
  });
  // Find and replace text.
  requests.push({
    findReplace: {
      find: find,
      replacement: replacement,
      allSheets: true,
    },
  });
  try {
    // Add additional requests (operations) ...
    const batchUpdateRequest = {requests: requests};
    gapi.client.sheets.spreadsheets.batchUpdate({
      spreadsheetId: spreadsheetId,
      resource: batchUpdateRequest,
    }).then((response) => {
      const findReplaceResponse = response.result.replies[1].findReplace;
      console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`);
      if (callback) callback(response);
    });
  } catch (err) {
    document.getElementById('content').innerText = err.message;
    return;
  }
}

Node.js

sheets/snippets/sheets_batch_update.js
/**
 * Updates the Spreadsheet title. Finds and replaces a string in the sheets.
 * @param {string} spreadsheetId The Spreadsheet to update
 * @param {string} title The new Spreadsheet title
 * @param {string} find The text to find
 * @param {string} replacement The text to replace
 * @return {obj} holding the information regarding the replacement of strings
 */
async function batchUpdate(spreadsheetId, title, find, replacement) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  const service = google.sheets({version: 'v4', auth});
  const requests = [];
  // Change the spreadsheet's title.
  requests.push({
    updateSpreadsheetProperties: {
      properties: {
        title,
      },
      fields: 'title',
    },
  });
  // Find and replace text.
  requests.push({
    findReplace: {
      find,
      replacement,
      allSheets: true,
    },
  });
  // Add additional requests (operations) ...
  const batchUpdateRequest = {requests};
  try {
    const response = await service.spreadsheets.batchUpdate({
      spreadsheetId,
      resource: batchUpdateRequest,
    });
    const findReplaceResponse = response.data.replies[1].findReplace;
    console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`);
    return response;
  } catch (err) {
    // TODO (developer) - Handle exception
    throw err;
  }
}

PHP

sheets/snippets/src/SpreadsheetBatchUpdate.php
use Google\Client;
use Google\Service\Drive;
use Google\Service\Sheets\BatchUpdateSpreadsheetRequest;

/**
 * to batch update a spreadsheet
 */
function batchUpdate($spreadsheetId, $title, $find, $replacement)
    {   
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
        $client = new Google\Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Google\Service\Drive::DRIVE);
        $service = new Google_Service_Sheets($client);
        try{
            //execute the request
            $requests = [
                new Google_Service_Sheets_Request([
              'updateSpreadsheetProperties' => [
                  'properties' => [
                      'title' => $title
                    ],
                    'fields' => 'title'
              ]
          ]),
          new Google_Service_Sheets_Request([
              'findReplace' => [
                  'find' => $find,
                  'replacement' => $replacement,
                  'allSheets' => true
                  ]
                  ])
                ];
                $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
                    'requests' => $requests
                ]);
        $response = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
        $findReplaceResponse = $response->getReplies()[1]->getFindReplace();
        printf("%s replacements made.\n",
        $findReplaceResponse->getOccurrencesChanged());
        return $response;
    }
    catch(Exception $e) {
        // TODO(developer) - handle error appropriately
        echo 'Message: ' .$e->getMessage();
      }
    }

Python

sheets/snippets/sheets_batch_update.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def sheets_batch_update(spreadsheet_id, title, find, replacement):
  """
  Update the sheet details in batch, the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member

  try:
    service = build("sheets", "v4", credentials=creds)

    requests = []
    # Change the spreadsheet's title.
    requests.append(
        {
            "updateSpreadsheetProperties": {
                "properties": {"title": title},
                "fields": "title",
            }
        }
    )
    # Find and replace text
    requests.append(
        {
            "findReplace": {
                "find": find,
                "replacement": replacement,
                "allSheets": True,
            }
        }
    )
    # Add additional requests (operations) ...

    body = {"requests": requests}
    response = (
        service.spreadsheets()
        .batchUpdate(spreadsheetId=spreadsheet_id, body=body)
        .execute()
    )
    find_replace_response = response.get("replies")[1].get("findReplace")
    print(
        f"{find_replace_response.get('occurrencesChanged')} replacements made."
    )
    return response

  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  sheets_batch_update("spreadsheet_id", "title", "find", "replacement")

Ruby

sheets/snippets/lib/spreadsheet_snippets.rb
requests = []
# Change the name of sheet ID '0' (the default first sheet on every
# spreadsheet)
requests.push({
                update_sheet_properties: {
                  properties: { sheet_id: 0, title: 'New Sheet Name' },
                  fields:     'title'
                }
              })
# Find and replace text
requests.push({
                find_replace: {
                  find:        find,
                  replacement: replacement,
                  all_sheets:  true
                }
              })
# Add additional requests (operations) ...

body = { requests: requests }
result = service.batch_update_spreadsheet(spreadsheet_id, body, {})
find_replace_response = result.replies[1].find_replace
puts "#{find_replace_response.occurrences_changed} replacements made."