/** * 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.letupdateSpreadsheetPropertiesRequest=Sheets.newUpdateSpreadsheetPropertiesRequest();updateSpreadsheetPropertiesRequest.properties=Sheets.newSpreadsheetProperties();updateSpreadsheetPropertiesRequest.properties.title=title;updateSpreadsheetPropertiesRequest.fields='title';// Find and replace text.letfindReplaceRequest=Sheets.newFindReplaceRequest();findReplaceRequest.find=find;findReplaceRequest.replacement=replacement;findReplaceRequest.allSheets=true;letrequests=[Sheets.newRequest(),Sheets.newRequest()];requests[0].updateSpreadsheetProperties=updateSpreadsheetPropertiesRequest;requests[1].findReplace=findReplaceRequest;letbatchUpdateRequest=Sheets.newBatchUpdateSpreadsheetRequest();batchUpdateRequest.requests=requests;// Add additional requests (operations)constresult=Sheets.Spreadsheets.batchUpdate(batchUpdateRequest,spreadsheetId);returnresult;}catch(err){// TODO (developer) - Handle exceptionconsole.log('Failedwitherror%s',err.message);}};
importcom.google.api.client.googleapis.json.GoogleJsonError;importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.sheets.v4.Sheets;importcom.google.api.services.sheets.v4.SheetsScopes;importcom.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest;importcom.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse;importcom.google.api.services.sheets.v4.model.FindReplaceRequest;importcom.google.api.services.sheets.v4.model.FindReplaceResponse;importcom.google.api.services.sheets.v4.model.Request;importcom.google.api.services.sheets.v4.model.SpreadsheetProperties;importcom.google.api.services.sheets.v4.model.UpdateSpreadsheetPropertiesRequest;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;/* Class to demonstrate the use of Spreadsheet Batch Update API */publicclassBatchUpdate{/** * 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. */publicstaticBatchUpdateSpreadsheetResponsebatchUpdate(StringspreadsheetId,Stringtitle,Stringfind,Stringreplacement)throwsIOException{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Create the sheets API clientSheetsservice=newSheets.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Sheets samples").build();List<Request>requests=newArrayList<>();BatchUpdateSpreadsheetResponseresponse=null;try{// Change the spreadsheet's title.requests.add(newRequest().setUpdateSpreadsheetProperties(newUpdateSpreadsheetPropertiesRequest().setProperties(newSpreadsheetProperties().setTitle(title)).setFields("title")));// Find and replace text.requests.add(newRequest().setFindReplace(newFindReplaceRequest().setFind(find).setReplacement(replacement).setAllSheets(true)));BatchUpdateSpreadsheetRequestbody=newBatchUpdateSpreadsheetRequest().setRequests(requests);response=service.spreadsheets().batchUpdate(spreadsheetId,body).execute();FindReplaceResponsefindReplaceResponse=response.getReplies().get(1).getFindReplace();System.out.printf("%d replacements made.",findReplaceResponse.getOccurrencesChanged());}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelyGoogleJsonErrorerror=e.getDetails();if(error.getCode()==404){System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId);}else{throwe;}}returnresponse;}}
/** * 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 */asyncfunctionbatchUpdate(spreadsheetId,title,find,replacement){const{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/spreadsheets',});constservice=google.sheets({version:'v4',auth});constrequests=[];// 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) ...constbatchUpdateRequest={requests};try{constresponse=awaitservice.spreadsheets.batchUpdate({spreadsheetId,resource:batchUpdateRequest,});constfindReplaceResponse=response.data.replies[1].findReplace;console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`);returnresponse;}catch(err){// TODO (developer) - Handle exceptionthrowerr;}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefsheets_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-membertry:service=build("sheets","v4",credentials=creds)requests=[]# Change the spreadsheet's title.requests.append({"updateSpreadsheetProperties":{"properties":{"title":title},"fields":"title",}})# Find and replace textrequests.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.")returnresponseexceptHttpErroraserror:print(f"An error occurred: {error}")returnerrorif__name__=="__main__":sheets_batch_update("spreadsheet_id","title","find","replacement")
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 textrequests.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_replaceputs"#{find_replace_response.occurrences_changed} replacements made."
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2024-12-21 (世界標準時間)。"],[[["The `spreadsheets.batchUpdate` method allows for updating various spreadsheet details like dimensions, formats, and named ranges in a single request."],["This method supports a wide range of operations categorized as Add, Update, and Delete for manipulating spreadsheet elements."],["Requests are grouped in batches to ensure that dependent changes are written or none are if one fails."],["Field masks can be used to selectively update specific fields within an object."],["Responses to batch updates typically provide information about the added or modified objects, like IDs."]]],["The `spreadsheets.batchUpdate` method modifies spreadsheet details like dimensions, cell formats, named ranges, and conditional formatting. It groups changes, ensuring that if one request fails, no changes are written. Operations include adding, duplicating, updating, setting, and deleting objects. The method accepts multiple `Request` objects, offering various actions such as manipulating properties, sheets, dimensions, cells, and named ranges. \"Update\" requests often use field masks to specify which fields to change. Responses from requests are returned in an array, mirroring the order of the input requests.\n"]]