1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GASでGoogleスプレッドシートを使いやすくするためのクラス

Last updated at Posted at 2021-12-18

イマイチ使いたい形でAPIを提供してくれてないので、GoogleSheetクラスをラップするクラスを書いた。

あるタスクで利用した用途によっているので、今後拡張する必要あり。

class WrappedWorkSheet {
  constructor(sheet) {
    this.sheet               = sheet
    this.data                = this.sheet.getDataRange().getValues()
    this.header              = this.data.slice(0,1)[0] 
    this.body                = this.data.slice(1,) 
    this.latestRow           = this.data.slice(-1,)[0]
    this.latestRowWithHeader = Object.fromEntries(this.latestRow.map((e, index) => [this.header[index], e]))
    this.latestRowPos        = this.data.length
  }

  static build(sheetId, sheetName) {
    // TODO: あってるっぽいが要チェック。継承した場合用
    const self = this
    return new self(SpreadsheetApp.openById(sheetId).getSheetByName(sheetName))
  }

  getLatestRowWithHeader() {
    return this.latestRowWithHeader
  }

  getLatestRowPos() {
    return this.latestRowPos
  }

  updateWholeRow(rowPos, newValues) {
    this.sheet.getRange(rowPos, 1, 1, this.sheet.getLastColumn()).clear({ contentsOnly: true })
    this.sheet.getRange(rowPos, 1, 1, this.sheet.getLastColumn()).setValues([newValues])
  }
    
  updateValueOfRow(rowPos, label, newValue) {
    const colPos = this.findTargetColPosition(label)
    this.updateValue(rowPos, colPos, newValue)
  }
   
  findTargetRowPosition(label, targetValue) {
    const targetColumnPosition = this.findTargetColPosition(label)
    if (targetColumnPosition === null) { return null }
  
    const ValuesInTargetColumn = this.getColumnValues(targetColumnPosition)
    return this.getPosition(ValuesInTargetColumn, targetValue)
  }
  
  findTargetColPosition(headerLabel) {
    return this.getPosition(this.header, headerLabel)
  }

  // basic utility and delegation

  updateValue(rowPos, colPos, value) {
    this.sheet.getRange(rowPos, colPos).setValue(value)
  }
  
  getPosition(values, value) {
    const position = values.indexOf(value)
    return position == -1 ? null : position + 1
  }
  
  getColumnValues(columnPoistion){
    return this.sheet.getRange(1, columnPoistion, this.sheet.getLastRow()).getValues().flat()
  } 

  appendRow(row) {
    this.sheet.appendRow(row)
  }

  deleteRow(rowPos) {
    this.sheet.deleteRow(rowPos)
  }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?