스프레드시트 업데이트

이 문서에서는 spreadsheets.batchUpdate 메서드를 spreadsheets 리소스에서 사용하는 기본사항을 설명합니다.

스프레드시트에는 셀에 포함된 값 데이터 외에도 다음과 같은 여러 유형의 데이터가 포함됩니다.

  • 크기
  • 셀 형식 및 테두리
  • 이름이 지정된 범위
  • 보호된 범위
  • 조건부 서식

이러한 데이터는 스프레드시트의 모양과 작업을 제어하는 여러 종류의 데이터 중 일부입니다. spreadsheets.batchUpdate 메서드를 사용하면 이러한 스프레드시트 세부정보를 업데이트할 수 있습니다. 변경사항은 일괄 처리로 그룹화되므로 하나의 요청이 실패하면 다른 (잠재적으로 종속된) 변경사항은 작성되지 않습니다.

셀 값 데이터를 읽고 써야 하는 경우 spreadsheets.values 리소스를 셀 값 읽기 및 쓰기에 설명된 대로 사용할 수도 있습니다.

작업 유형

spreadsheets.batchUpdate 메서드에서 지원하는 특정 작업은 다음과 같은 광범위한 작업 유형으로 그룹화할 수 있습니다.

카테고리 설명
추가 (및 복제)새 객체를 추가합니다 (복제 요청에서와 같이 이전 객체를 기반으로 하는 경우도 있음).
업데이트 (및 설정)객체의 특정 속성을 업데이트합니다. 일반적으로 이전 속성은 그대로 둡니다 (반면 설정 요청은 이전 데이터를 덮어씁니다).
삭제객체를 삭제합니다.

이러한 카테고리는 다음 섹션에서 특정 작업의 동작을 설명하는 데 사용됩니다.

일괄 업데이트 작업

spreadsheets.batchUpdate 메서드는 하나 이상의 Request 객체를 가져와서 작동하며 각 객체는 실행할 단일 종류의 요청을 지정합니다. 다음 표에는 리소스 객체 및 작업 유형별로 그룹화된 일괄 업데이트 요청 유형이 나와 있습니다.

객체 추가 / 복제 업데이트 / 설정 삭제
BandedRange AddBandingRequest UpdateBandingRequest DeleteBandingRequest
Borders UpdateBordersRequest
Cells (값, 형식, 데이터 유효성 검사 등 포함) InsertRangeRequest RepeatCellRequest
UpdateCellsRequest
AppendCellsRequest
DeleteRangeRequest
ConditionalFormatRule AddConditionalFormatRuleRequest UpdateConditionalFormatRuleRequest DeleteConditionalFormatRuleRequest
DataSource AddDataSourceRequest UpdateDataSourceRequest
RefreshDataSourceRequest
CancelDataSourceRefreshRequest
DeleteDataSourceRequest
DataValidationRule SetDataValidationRequest
developerMetadata CreateDeveloperMetadataRequest UpdateDeveloperMetadataRequest DeleteDeveloperMetadataRequest
Dimension (DimensionRange 포함) InsertDimensionRequest
AppendDimensionRequest
UpdateDimensionPropertiesRequest
MoveDimensionRequest
AutoResizeDimensionsRequest
DeleteDimensionRequest
DimensionGroup AddDimensionGroupRequest UpdateDimensionGroupRequest DeleteDimensionGroupRequest
EmbeddedChart AddChartRequest UpdateChartSpecRequest
UpdateEmbeddedObjectPositionRequest
UpdateEmbeddedObjectBorderRequest
DeleteEmbeddedObjectRequest
FilterView (BasicFilter 포함) AddFilterViewRequest
DuplicateFilterViewRequest
UpdateFilterViewRequest
SetBasicFilterRequest
ClearBasicFilterRequest
DeleteFilterViewRequest
셀 병합 (MergeType 포함) MergeCellsRequest UnmergeCellsRequest
NamedRange AddNamedRangeRequest UpdateNamedRangeRequest DeleteNamedRangeRequest
ProtectedRange AddProtectedRangeRequest UpdateProtectedRangeRequest DeleteProtectedRangeRequest
Sheets AddSheetRequest
DuplicateSheetRequest
UpdateSheetPropertiesRequest DeleteSheetRequest
Slicer AddSlicerRequest UpdateSlicerSpecRequest
SpreadsheetProperties UpdateSpreadsheetPropertiesRequest
Table AddTableRequest UpdateTableRequest DeleteTableRequest

데이터 조작 요청

데이터 조작을 위한 사용자 작업을 모방하는 몇 가지 추가 요청도 있습니다.

요청 설명
AutoFillRequest 기존 데이터를 기반으로 더 많은 데이터를 자동으로 채웁니다.
CopyPasteRequest 한 영역에서 데이터를 복사하여 다른 영역에 붙여넣습니다.
CutPasteRequest 한 영역에서 데이터를 잘라내어 다른 영역에 붙여넣습니다.
DeleteDuplicatesRequest 셀 범위의 지정된 열에 중복된 값이 포함된 행을 삭제합니다.
FindReplaceRequest 일부 텍스트의 발생을 찾아 다른 텍스트로 바꿉니다.
PasteDataRequest 데이터 (HTML 또는 구분됨)를 시트에 붙여넣습니다.
RandomizeRangeRequest 범위의 행 순서를 무작위로 지정합니다.
SortRangeRequest 범위의 데이터를 정렬합니다.
TextToColumnsRequest 텍스트 열을 여러 텍스트 열로 변환합니다.
TrimWhitespaceRequest 공백 (예: 공백, 탭, 줄바꿈)이 있는 셀을 자릅니다.

Google Sheets의 셀 및 행 한도에 관해 자세히 알아보려면 Google Drive에 저장할 수 있는 파일을 참고하세요.

필드 마스크를 사용하여 특정 필드 업데이트

많은 업데이트 요청에 FieldMask가 필요합니다. 필드 마스크는 객체에서 업데이트할 필드를 나타내는 데 사용되는 쉼표로 구분된 필드 목록이며 다른 모든 필드는 변경되지 않은 상태로 둡니다. 필드 마스크를 사용하면 요청에 지정되지 않은 필드가 실수로 덮어쓰이는 것을 방지할 수 있습니다.

필드 마스크에 관한 자세한 내용은 필드 마스크로 업데이트를 참고하세요.

다음 코드 샘플은 UpdateSpreadsheetPropertiesRequest 를 사용하여 스프레드시트의 제목만 업데이트하는 방법을 보여줍니다.

요청

POST https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate

요청 본문

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

TITLE을 스프레드시트의 새 제목으로 바꿉니다.

일괄 업데이트 응답

스프레드시트를 업데이트할 때 일부 종류의 요청은 응답을 반환할 수 있습니다. 이러한 응답은 배열로 반환되며 각 응답은 해당 요청과 동일한 색인을 차지합니다. 일부 요청에는 응답이 없으며 이러한 요청의 경우 응답이 비어 있습니다.

일반적으로 '추가' 요청에는 추가된 객체의 ID와 같은 정보를 반환하는 응답이 있습니다. 지원되는 응답 목록은 Responses를 참고하세요.

코드 샘플: 스프레드시트 일괄 업데이트

다음 코드 샘플은 이러한 작업을 실행하는 방법을 보여줍니다.

  1. title 변수를 사용하여 스프레드시트의 제목을 업데이트합니다.
  2. findreplacement 변수를 사용하여 스프레드시트에서 셀 값을 찾고 바꿉니다.

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.
    const updateSpreadsheetPropertiesRequest =
      Sheets.newUpdateSpreadsheetPropertiesRequest();
    updateSpreadsheetPropertiesRequest.properties =
      Sheets.newSpreadsheetProperties();
    updateSpreadsheetPropertiesRequest.properties.title = title;
    updateSpreadsheetPropertiesRequest.fields = "title";

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

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

    const 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);
  }
};

자바

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
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Performs a batch update on a spreadsheet.
 * Updates the spreadsheet title and finds and replaces a string.
 * @param {string} spreadsheetId The ID of the spreadsheet to update.
 * @param {string} title The new title for the spreadsheet.
 * @param {string} find The string to find.
 * @param {string} replacement The string to replace the found string with.
 * @return {Promise<object>} The response from the batch update.
 */
async function batchUpdate(spreadsheetId, title, find, replacement) {
  // Authenticate with Google and get an authorized client.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  // Create a new Sheets API client.
  const service = google.sheets({version: 'v4', auth});

  // Create a list of requests to be executed in the batch update.
  const requests = [];

  // Request to change the spreadsheet's title.
  requests.push({
    updateSpreadsheetProperties: {
      properties: {
        title,
      },
      fields: 'title',
    },
  });

  // Request to find and replace text.
  requests.push({
    findReplace: {
      find,
      replacement,
      allSheets: true,
    },
  });

  // Add more requests here if needed.

  // Create the batch update request.
  const batchUpdateRequest = {requests};

  // Execute the batch update request.
  const response = await service.spreadsheets.batchUpdate({
    spreadsheetId,
    requestBody: batchUpdateRequest,
  });

  // Get the response from the find and replace request and log the number of occurrences.
  const findReplaceResponse = response.data.replies[1].findReplace;
  console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`);
  return response;
}

PHP

sheets/snippets/src/SpreadsheetBatchUpdate.php
<?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."