Microsoft 365 Excel: 複数セル値, 一括更新(範囲指定)
Microsoft 365 Excel: Cells Value, Bulk Update (range)
シート内の指定された範囲のセル(テーブル型の表を想定)のデータを一括更新します。(改行を含む値は指定できません)
Configs for this Auto Step
- conf_OAuth2
- C1: OAuth2 設定 *
- conf_Url
- C2: 入力先のブックの URL *
- conf_Title
- C3: 入力先のシートのタイトル *#{EL}
- conf_CellFrom
- C4: 対象範囲のセルfrom *#{EL}
- conf_CellTo
- C5: 対象範囲のセルto *#{EL}
- conf_Tsv
- C6: セルを更新するための設定TSV#{EL}
Script (click to open)
// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
// - Scope: https://graph.microsoft.com/Files.ReadWrite.All offline_access
// - Consumer Key: (Get by Microsoft Azure Active Directory)
// - Consumer Secret: (Get by Microsoft Azure Active Directory)
const GRAPH_URI = "https://graph.microsoft.com/v1.0/";
main();
function main(){
//// == Config Retrieving / 工程コンフィグの参照 ==
const oauth2 = configs.get( "conf_OAuth2" );
const bookUrl = retrieveBookUrl();
const sheetName = configs.get( "conf_Title" );
if(sheetName === "" || sheetName === null){
throw "Sheet Title is empty.";
}
const cell1 = configs.get( "conf_CellFrom" );
const cell2 = configs.get( "conf_CellTo" );
const tsv = configs.get( "conf_Tsv" );
const json = retrieveJson(tsv);
//engine.log("json:" + json + "");
//// == Calculating / 演算 ==
// Access to the API 1st(Get Book Info)
const bookInfo = getFileInfoByUrl( bookUrl, oauth2 );
const worksheetId = getWorksheetId(bookInfo, sheetName, oauth2);
// Access to the API 2nd(PATCH)
patchData( bookInfo, worksheetId, cell1,cell2, json, oauth2);
}
/**
* config からブックの URL を読み出す、空ならエラー
* @return {String} ブックの URL
*/
function retrieveBookUrl() {
const bookUrlDef = configs.getObject( "conf_Url" );
let bookUrl;
if ( bookUrlDef === null ) {
bookUrl = configs.get( "conf_Url" )
}else{
bookUrl = engine.findData( bookUrlDef );
}
if ( bookUrl === "" || bookUrl === null){
throw "Book URL is empty."
}
return bookUrl;
}
/**
* 設定TSVを元に更新データJSON文字列を生成
* @param {String} text もととなるTSV
* @return {String} JSON文字列
*/
function retrieveJson(tsv) {
let json = '{"values" : [';
const arrLine = tsv.split(/\r\n|\n/);
engine.log("arrLine:"+arrLine.length)
for ( let i = 0; i < arrLine.length; i++ ) {
if ( i > 0 ) {
json += ','
}
json += '['
const arrCell = arrLine[i].split("\t");
engine.log("arrCell:"+arrCell.length)
for ( let j = 0; j < arrCell.length; j++ ) {
if ( j > 0 ) {
json += ','
}
if ( arrCell[j] === "" ) {
json += 'null'
} else {
json += '"' + arrCell[j] + '"'
}
}
json += ']'
}
json += ']}';
return json;
}
/**
* フォルダの URL からファイル情報(ドライブ ID とファイル ID)を取得し、
* オブジェクトで返す(URL が空の場合はエラーとする)
* @param {String} fileUrl フォルダの URL
* @param {String} oauth2 OAuth2 設定
* @return {Object} fileInfo ファイル情報 {driveId, fileId}
*/
function getFileInfoByUrl( fileUrl, oauth2 ) {
let fileInfo;
if ( fileUrl !== "" && fileUrl !== null ) {
// 分割代入
const {
id,
parentReference: {
driveId
}
} = getObjBySharingUrl( fileUrl, oauth2 );
fileInfo = {driveId: `drives/${driveId}`, fileId: id};
}
return fileInfo;
}
/**
* OneDrive のドライブアイテム(ファイル、フォルダ)のメタデータを取得し、JSON オブジェクトを返す
* API の仕様:https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
* @param {String} sharingUrl ファイルの共有 URL
* @param {String} oauth2 OAuth2 設定
* @return {Object} responseObj ドライブアイテムのメタデータの JSON オブジェクト
*/
function getObjBySharingUrl( sharingUrl, oauth2 ) {
if (sharingUrl === "" || sharingUrl === null) {
throw `Sharing URL is empty.`;
}
// encoding sharing URL
const encodedSharingUrl = encodeSharingUrl(sharingUrl);
// API Request
const response = httpClient.begin()
.authSetting( oauth2 )
.get( `${GRAPH_URI}shares/${encodedSharingUrl}/driveItem` );
const responseStr = logAndJudgeError(response, "GET");
return JSON.parse( responseStr );
}
/**
* 共有URLをunpadded base64url 形式にエンコードする
* @param {String} sharingUrl 共有 URL
* @return {String} encodedSharingUrl エンコードされた共有 URL
*/
function encodeSharingUrl( sharingUrl ) {
let encodedSharingUrl = base64.encodeToUrlSafeString( sharingUrl );
while ( encodedSharingUrl.slice(-1) === '=' ) {
encodedSharingUrl = encodedSharingUrl.slice(0,-1);
}
return `u!${encodedSharingUrl}`;
}
/**
* ワークシートの ID を取得する
* @param {Object} bookInfo
* @param {String} bookInfo.driveId ワークブックのドライブ ID
* @param {String} bookInfo.fileId ワークブックのファイル ID
* @param {String} sheetName シートの名前
* @param {String} oauth2 OAuth2 設定
*/
function getWorksheetId({driveId, fileId}, sheetName, oauth2) {
const getWorksheetsUrl = `${GRAPH_URI}${driveId}/items/${fileId}/workbook/worksheets`;
const response = httpClient.begin()
.authSetting(oauth2)
.get(getWorksheetsUrl);
const responseStr = logAndJudgeError(response, "2nd GET");
const jsonRes = JSON.parse(responseStr);
const worksheet = jsonRes.value.find(worksheet => worksheet.name === sheetName);
if (worksheet === undefined) {
throw 'Worksheet not found.';
}
return worksheet.id;
}
/**
* 指定シートの指定セルのデータを更新する
* @param {Object} bookInfo
* @param {String} bookInfo.driveId ワークブックのドライブ ID
* @param {String} bookInfo.fileId ワークブックのファイル ID
* @param {String} worksheetId シートの ID
* @param {String} cell1 更新範囲のセルfrom
* @param {String} cell2 更新範囲のセルto
* @param {String} json 更新データJSON文字列
* @param {String} oauth2 OAuth2 設定
*/
function patchData( {driveId, fileId}, worksheetId, cell1, cell2, json, oauth2 ){
const patchUri = `${GRAPH_URI}${driveId}/items/${fileId}/workbook/worksheets/${encodeURIComponent(worksheetId)}/range(address='${cell1}:${cell2}')/`;
const response = httpClient.begin()
.authSetting( oauth2 )
.body( json, "application/json" )
.patch( patchUri );
logAndJudgeError(response, "PATCH");
}
/**
* 新しい行に追加するデータを、JSON 形式に変換する
* @param {Array} values データの入った配列
* @return {JSON Object} 変換した JSON オブジェクト
*/
function makeRequestToAdd(values){
let request = {
values : [[]]
};
if(values[0] === "" || values[0] === null){
request.values[0].push(null);
} else {
if(values[0].length > 32767){
throw "Can't set text over 32,767 character.";
}
request.values[0].push(values[0]);
}
return request;
}
/**
* ログの出力と、エラー発生時のスローを行う
* @param {HttpResponseWrapper} response リクエストの応答
* @param {String} requestType リクエストをどの形式で行ったか("GET" or "POST" or "PATCH")
* @return {String} responseStr レスポンスの文字列
*/
function logAndJudgeError(response, requestType){
const responseStr = response.getResponseAsString();
const status = response.getStatusCode();
if(status >= 300){
const accessLog = `---${requestType} request--- ${status}\n${responseStr}\n`;
engine.log(accessLog);
throw `Failed in ${requestType} request. status: ${status}`;
}
return responseStr;
}
Download
- excel-cells-bulk-update.xml
- 2024-08-01 (C) Questetra, Inc. (MIT License)
自由改変可能な JavaScript (ECMAScript) コードです。いかなる保証もありません。
(アドオン自動工程のインストールは Professional editionでのみ可能です)
(アドオン自動工程のインストールは Professional editionでのみ可能です)
Notes
- Microsoft365 系のサービスとの連携設定について
- Microsoft365(Azure Active Directory)側のアプリケーション登録の方法
- Questetra 側の HTTP 認証設定の方法
- “OneDrive へクラウドワークフロー Questetra からファイル出力する方法”
- “2.2: Questetra 側の OAuth 設定”
- ※注意※ Excel Online ファイルが SharePoint Online(SPO)のドキュメントライブラリ上にある場合、指定すべきスコープが異なる
- SPOドキュメントライブラリ上ではない →https://graph.microsoft.com/Files.ReadWrite offline_access
- SPOドキュメントライブラリ上にある →https://graph.microsoft.com/Sites.ReadWrite.All offline_access
- “OneDrive へクラウドワークフロー Questetra からファイル出力する方法”
- シート名にカッコ等の記号が入っている場合にはエラーになることがあります。エラーとなった場合にはシート名の変更を検討してください。
Capture

