๐ŸšงSheetMethods

GAS โŸฉ app โŸฉ sheet

ๅˆฉ็”จ mixin ็š„ๆ–นๅผ๏ผŒ่ฎ“ๅ€‹ๅˆฅ็š„ Sheet ็‰ฉไปถๆ“ๆœ‰ๆ–นไพฟ็š„ methods๏ผš

 Object.assign(sheet, SheetMethods);       // โญ extend `Sheet`
/**
 * common methods for a sheet
 * - deleteExtraColumns()
 * - deleteExtraRows()
 * - writeObjects(obj, {row=1, col=1, clearSheet=false})
 * @mixin
 */
const SheetMethods = {

  /**
   * ๐Ÿ”ธ delete extra columns in a sheet
   * @example
   * sheet.deleteExtraColumns()
   */
  deleteExtraColumns(){
    const j = this.getMaxColumns(); 
    const i = this.getLastColumn();
    if (j > i) this.deleteColumns(i+1, j-i);
  },

  /**
   * ๐Ÿ”ธ delete extra rows in a sheet
   * @example
   * sheet.deleteExtraRows()
   */
  deleteExtraRows(){
    var j = this.getMaxRows(); 
    var i = this.getLastRow();
    if (j > i) this.deleteRows(i+1, j-i);
  },

  /**
   * ๐Ÿ”ธ write objects' data into sheet
   * @param {[object]} objs - array of objects (all with same properties)
   * @param {number} row - first row number of the range where data is written into.
   * @param {number} col - first column number of the range
   * @param {boolean} clearSheet - decide whether or not to clear entire sheet first.
   */
  writeObjects(objs, {
    row   = 1, 
    col   = 1, 
    clearSheet = false
  }={}) {

    // get keys from first object
    let keys = Object.keys(objs[0]);

    // dimensions of the data range.
    var rows = objs.length;
    var cols = keys.length;
    
    // +1 row for the header row.
    let range = this.getRange(row, col, rows + 1, cols);

    // objects -> 2D array
    const values = [];
    values.push(keys);        // 1st row: header

    objs.forEach( obj => {
      const row = keys.map(key => obj[key]);   // obj --> [v1, v2, ...]
      values.push(row);
    }); 
    
    // clear sheet if necessary
    if (clearSheet) this.clear();

    // write 2D values into range
    range.setValues(values);
  },

};

Last updated