Skip to content

Instantly share code, notes, and snippets.

@hkurosawa
Last active October 31, 2020 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkurosawa/4c5aa3dab5310e34a8cf325bd5fad538 to your computer and use it in GitHub Desktop.
Save hkurosawa/4c5aa3dab5310e34a8cf325bd5fad538 to your computer and use it in GitHub Desktop.
Google App Scriptを使ってスプレッドシートに任意のkey-valueを保存する
/**
* 任意のシートにkey-valueを保存する
*/
class Variables{
constructor (sheet_name="variables") {
let app = SpreadsheetApp.getActiveSpreadsheet();
this.sheet = app.getSheetByName(sheet_name);
if (!this.sheet) {
//シートが存在しない場合は末尾に追加
app.insertSheet(sheet_name, app.getSheets().length);
this.sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name);
}
}
/**
* keyに値を設定する。ない場合には追加する
*/
set_value (key, val) {
//let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name);
let idx = this.search_row_index(key);
if (idx > 0) {
this.sheet.getRange(idx, 2).setValue(val);
} else {
//keyが存在しない場合は追加する
this.sheet.appendRow([key, val]);
}
}
/**
* keyの値を取得する
*/
get_value (key, val) {
//let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name);
let range = this.sheet.getRange(this.search_row_index(key), 2);
return range.getValue();
}
/**
* keyを削除する
*/
delete_key (key) {
//let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name);
let idx = this.search_row_index(key);
if (idx > 0) {
this.sheet.deleteRow(idx)
}
}
/**
* keyの行番号を返す
*/
search_row_index(key){
//let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name);
let range = this.sheet.getDataRange();
range = this.sheet.getRange(1, 1, range.getHeight());
//range指定は1始まりなので加算
return range.getValues().map(i => i[0]).indexOf(key) + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment