LoginSignup
47
47

More than 5 years have passed since last update.

Handsontable 使い方メモ4(メソッド)

Last updated at Posted at 2016-04-11

基本
グリッドのオプション
セル・カラムのオプション

※全てのメソッドは網羅していません。

全てのメソッドを確認したい場合は、 公式ドキュメント を参照。

メソッド

alter:行・列を挿入・削除する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]
    ]
});

table.alter('insert_row', 1);
table.alter('insert_col', 2);

handsontable.jpg

  • 第一引数に、処理の種類を指定する。
    • insert_row, insert_col, remove_row, remove_col のいずれか。
  • 第二引数に、処理対象の行・列を指定するインデックスを渡す。
  • 第三引数に、挿入(削除)する行(列)数を指定する。
    • デフォルトは 1

clear:グリッドをクリアする

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]
    ]
});

table.clear();

handsontable.jpg

  • グリッドの中身を全てクリアする。

countCols, countRows:列・行数を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2],
        [1, 2],
        [1, 2]
    ]
});

var cols = table.countCols();
var rows = table.countRows();

console.log('cols=' + cols + ', rows=' + rows);

handsontable.jpg

  • countCols で列数を、 countRows で行数を取得できる。

countEmptyCols, countEmptyRows:空の行・列数を習得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [   1, null,    2],
        [null, null, null],
        [null, null,    2],
        [   1, null,    2],
        [null, null, null]
    ]
});

var cols = table.countEmptyCols();
var rows = table.countEmptyRows();

console.log('cols=' + cols + ', rows=' + rows);
実行結果
cols=1, rows=2
  • 全てが空の行(列)の数を習得できる。

countCols, countRows:表示されている行・列数を習得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [null, null, null],
        [   1, null,    3]
    ]
});

var cols = table.countCols();
var rows = table.countRows();

console.log('cols=' + cols + ', rows=' + rows);
実行結果
cols=3, rows=2
  • 空かどうかに関わらず、行数・列数を習得できる。

count**Rows, count**Cols:色々な条件の行・列数を取得する

var grid = document.getElementById('grid');

var data = [];

for (var i=0; i<100; i++) {
    data.push([i]);
}

var table = new Handsontable(grid, {
    data: data,
    height: 100,
    width: 100,
    contextMenu: ['row_above']
});

document
    .querySelector('#button')
    .addEventListener('click', function() {
        console.log({
            countRows: table.countRows(),
            sourceRows: table.countSourceRows(),
            visibleRows: table.countVisibleRows(),
            renderedRows: table.countRenderedRows()
        });
    });

handsontable.gif

  • countRows[Cols]countSourceRows[Cols] が、実際の数を取得するっぽい。
    • 行を追加したり削除したりしても同じ値を返すので、違いはよくわからない。
    • countSourceRows は、 Rows だけで Cols 版が無い。
  • countVisibleRows[Cols] は、実際に目に見えている数を取得するっぽい。
    • でも、若干あやしい。
  • countRenderedRows[Cols] は、たぶん実際に DOM に吐かれている数を取得するっぽい。

deselectCell:セルの選択状態を解除する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

setTimeout(function() {
    table.deselectCell();
}, 2000);
  • 表示後すぐにセルを選択しても、約2秒後に deselectCell() が実行されて選択が解除される。

destroy:グリッドを削除する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.destroy();

handsontable.jpg

  • グリッドが完全に削除される。
  • グリッドの対象としていたタグ(#grid)は残る。

getCellMeta:セルのメタ情報を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    cell: [
        {
            col: 0,
            row: 0,
            type: 'numeric'
        }
    ]
});

console.log(table.getCellMeta(0, 0));
console.log(table.getCellMeta(0, 1));

handsontable.jpg

  • セルのメタ情報を取得できる。

getColHeader:ヘッダー名を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    colHeaders: ['one', 'two', 'three', 'four', 'five']
});

console.log(table.getColHeader());
console.log(table.getColHeader(2));
console.log(table.getColHeader(5));
console.log(table.getColHeader(-1));
実行結果
["one", "two", "three", "four", "five"]
three
F

  • 引数なしの場合は、ヘッダー名が配列で返される。
  • 列のインデックスを指定した場合、その列の名前が返される。
  • プラス方向にはみ出たインデックスを指定すると、デフォルトの列名(A, B, C...)が返される。
  • マイナス方向にはみ出たインデックスを指定すると、空文字が返される。

getColWidth, getRowHeight:列・列の幅・高さを取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    colWidths: [100, 120],
    rowHeights: [20, 80]
});

console.log(table.getColWidth(0) + ', ' + table.getRowHeight(0));
console.log(table.getColWidth(1) + ', ' + table.getRowHeight(1));

handsontable.jpg

  • getColWidth() で列の幅を、 getRowHeight() で行の高さを取得できる。

getCoords:指定した要素が存在する座標を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

var td = grid.querySelector('table tr:nth-child(2) td:nth-child(3)');

var coords = table.getCoords(td);

console.log(coords);

handsontable.jpg

  • セルの DOM オブジェクトを渡すと、そのセルの位置を持つオブジェクトが返される。

getData*():データを取得する

getDataAtCell():セルを指定してデータを取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [true, false, true],
        ['hoge', 'fuga', 'piyo']
    ]
});

console.log(table.getDataAtCell(0, 0));
console.log(table.getDataAtCell(1, 1));
console.log(table.getDataAtCell(2, 2));
実行結果
1
false
piyo
  • セルのインデックスを指定して値を取得する。

getDataAtCol:指定した列のデータを全て取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [true, false, true],
        ['hoge', 'fuga', 'piyo']
    ]
});

console.log(table.getDataAtCol(1));
実行結果
[2, false, "fuga"]
  • 列のインデックスを指定して、その列の全ての値を配列で取得する。

getDataAtRow:指定した行のデータを全て取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [true, false, true],
        ['hoge', 'fuga', 'piyo']
    ]
});

console.log(table.getDataAtRow(2));
実行結果
["hoge", "fuga", "piyo"]
  • 行のインデックスを指定して、その行の全ての値を配列で取得する。

getDataAtProp:指定した列名のデータを全て取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        {
            name: 'sato',
            age: 13
        },
        {
            name: 'suzuki',
            age: 15
        },
        {
            name: 'tanaka',
            age: 18
        }
    ]
});

console.log(table.getDataAtProp('name'));
実行結果
["sato", "suzuki", "tanaka"]
  • 列名を指定して、その列の全てのデータを配列で取得する。

getDataAtRowProp:行インデックスと列名を指定してデータを取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        {
            name: 'sato',
            age: 13
        },
        {
            name: 'suzuki',
            age: 15
        },
        {
            name: 'tanaka',
            age: 18
        }
    ]
});

console.log(table.getDataAtRowProp(0, 'age'));
実行結果
13
  • 行のインデックスと列名を指定して、そのセルのデータを取得する。

getData:データをまるごと、または範囲指定して取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
});

console.table(table.getData());
console.table(table.getData(0, 1, 1, 2));

handsontable.jpg

  • 引数無しの場合、全てのデータを取得する。
  • (fromRow, fromCol, toRow, toCol) の順番で範囲を指定子てデータを取得できる。

getSourceData:ソースデータをそのまま取得する

var grid = document.getElementById('grid');

var src = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

var table = new Handsontable(grid, {
    data: src
});

console.table(table.getSourceData());

handsontable.jpg

  • getData() と同じようにグリッドのデータを取得できる。
  • getData() との違いは、ソースデータそのものを取得している点。
var grid = document.getElementById('grid');

var src = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

var table = new Handsontable(grid, {
    data: src
});

console.table(table.getSourceData() === src);
console.table(table.getData() === src);
実行結果
true
false
  • getSourceData() で取得したデータは元となったデータ src と同じインスタンスを指している。
  • 一方で、 getData() で取得したデータは、元のデータとは別のインスタンスになっている。

getDataType:セルのデータ型を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    columns: [
        {type: 'text'},
        {type: 'numeric'},
        {type: 'numeric'},
        {type: 'autocomplete'}
    ]
});

console.log(table.getDataType(0, 0));
console.log(table.getDataType(0, 1));
console.log(table.getDataType(0, 2));
console.log(table.getDataType(0, 3));
console.log(table.getDataType(0, 1, 0, 2));
console.log(table.getDataType(0, 0, 0, 3));
実行結果
text
numeric
numeric
autocomplete
numeric
mixed
  • セルの座標、もしくは範囲を指定してセルの形式を取得できる。
  • 範囲を指定して取得したときに異なる型が混ざっている場合は mixed となる。

getSchema:設定で渡したスキーマを取得する

var grid = document.getElementById('grid');

var schema = {name: null, age: null};

var table = new Handsontable(grid, {
    dataSchema: schema
});

console.log(table.getSchema() === schema);
実行結果
true
  • オプションで渡した dataSchema を取得する。

selectCell, getSelected:セルを選択する・選択されたセルを取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.selectCell(0, 1, 2, 2);

var selected = table.getSelected();

console.log(selected);

handsontable.jpg

  • selectCell() でセルを選択できる。
    • 最初に2つが選択の開始位置、後ろ2つが選択の終了位置。
    • 開始位置だけの指定も可能。
  • getSelected() で、選択されたセルの座標を取得できる。

selectCellByProp:プロパティ名指定でセルを選択する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        {name: 'aaa', age: 12},
        {name: 'bbb', age: 15},
        {name: 'ccc', age: 18}
    ]
});

table.selectCellByProp(1, 'age');

handsontable.jpg

  • selectCell() の列を指定する部分がプロパティ名になった版。
  • 範囲指定も可能。

getValue:現在選択されているセルの値を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
});

table.selectCell(1, 2);
console.log(table.getValue());
実行結果
6

loadData:データを読み込む

var data = [
  {name: '佐藤', age: 25},
  {name: '鈴木', age: 11},
  {name: '田中', age: 21}
];

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {data: data});

// ★データを読み込む
table.loadData([
  {name: '御手洗', age: 31},
  {name: '東海林', age: 22}
]);

handsontable.JPG

  • loadData() メソッドを使えば、データを上書きで読み込みできる。

isEmptyCol, isEmptyRow:空列・行かどうかを確認する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [   1,    2, null],
        [   4,    5, null],
        [null, null, null]
    ]
});

console.log(table.isEmptyCol(1));
console.log(table.isEmptyCol(2));
console.log(table.isEmptyRow(1));
console.log(table.isEmptyRow(2));
実行結果
false
true
false
true
  • インデックス指定で行または列が空かどうかを確認できる。

populateFromArray:配列でデータを埋め込む

基本

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        ['a', 'b', 'c', 'd'],
        ['e', 'f', 'g', 'h'],
        ['i', 'j', 'k', 'l'],
        ['m', 'n', 'o', 'p'],
    ]
});

table.populateFromArray(0, 1, [
    [1, 2],
    [3, 4]
]);

handsontable.jpg

  • 第一、二引数で開始セルの位置を、第三引数で埋め込むデータを配列で指定する。
  • 元々存在していたセルは上書きされる。

埋め込む範囲を絞る

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.populateFromArray(1, 1, [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
], 2, 3);

handsontable.jpg

  • 第四、五引数で、貼り付け範囲を絞り込める。

繰り返しで貼り付ける

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.populateFromArray(0, 0, [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
], 4, 4);

handsontable.jpg

  • 第四、五引数で配列のサイズ以上の範囲を指定すると、その分だけ内容が繰り返されて貼り付けられる。

元あったセルをシフトさせる

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        ['a', 'b', 'c', 'd'],
        ['e', 'f', 'g', 'h'],
        ['i', 'j', 'k', 'l'],
        ['m', 'n', 'o', 'p'],
    ]
});

table.populateFromArray(0, 1, [
    [1, 2],
    [3, 4]
], 0, 0, 'populateFromArray', 'shift_down');

handsontable.jpg

  • 第七引数で、元のセルをシフトさせるかどうかを指定できる。
    • shift_down で下方向に、 shift_right で右方向にシフトする。
    • デフォルトは override で上書き。
  • 第六引数は、内部の共通実装がどのメソッドから呼ばれたかを識別すために使っているっぽい。
    • しかし、どう値を変更したら、どう挙動が変更するのかはよくわからない。
    • とりあえず、デフォルトの populateFromArray を設定しておいた。
  • shift_downshift_right を指定している場合は、範囲の指定を 0 にすることで配列のデータをそのまま渡せるようになる。
    • override のときに 0 を指定すると、値が埋めこまれなくなる。

propToCol:プロパティ名から列のインデックスを取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        {name: 'Sato', age: 14, sex: 'male'},
        {name: 'Suzuki', age: 16, sex: 'female'},
        {name: 'Tanaka', age: 18, sex: 'male'}
    ]
});

console.log('age = ' + table.propToCol('age'));

handsontable.jpg

  • プロパティ名を指定して、そのプロパティの列のインデックス値を取得できる。

colToProp:インデックスからプロパティ名を取得する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        {name: 'Sato', age: 14, sex: 'male'},
        {name: 'Suzuki', age: 16, sex: 'female'},
        {name: 'Tanaka', age: 18, sex: 'male'}
    ]
});

console.log('2 = ' + table.colToProp(2));

handsontable.jpg

  • propToCol の逆。

render:グリッドを再描画させる

var data = [
  ['佐藤', 28],
  ['鈴木', 19],
  ['田中', 25]
];

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {data: data});

// データを変更して
data.push(['山田', 22]);

// 再描画
table.render();

handsontable.JPG

  • データの内容を変更したあとで render() メソッドを実行すると、グリッドを再描画させられる。

setCellMeta:セルを指定してメタデータを設定する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.setCellMeta(1, 1, 'type', 'autocomplete');
table.setCellMeta(1, 1, 'source', ['one', 'two', 'three']);

handsontable.jpg

  • 第一、二引数でセルの位置を指定する。
  • 第三引数にメタデータのキー、第四引数にメタデータの値を指定する。

setCellMetaObject:セルを指定してオブジェクトでメタデータを設定する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.setCellMetaObject(1, 1, {
    type: 'autocomplete',
    source: ['one', 'two', 'three']
});
  • 複数のメタデータを一括で設定できる。
  • 実行結果は↑の setCellMeta() と同じ。

setDataAtCell:セルを指定して値を設定する

var grid = document.getElementById('grid');

var table = new Handsontable(grid);

table.setDataAtCell(1, 1, 'hoge');

handsontable.jpg

setDataAtRowProp:列名を指定してセルに値を設定する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    dataSchema: {
        hoge: null,
        fuga: null,
        piyo: null
    },
    columns: [
        {data: 'hoge'},
        {data: 'fuga'},
        {data: 'piyo'}
    ]
});

table.setDataAtRowProp(2, 'fuga', 'FUGA');

handsontable.jpg

spliceCol:列の要素を取り除きつつ、新しい要素を追加する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
});

var ret = table.spliceCol(1, 1, 2, 'X', 'Y', 'Z');
console.log(ret);

handsontable.jpg

  • Array.splice と同じような動作をするメソッド。
  • 第一引数と第二引数で開始位置を指定し、第三引数で取り除く要素数を指定する。
  • 第四引数には、新しく埋め込む値を可変長引数で指定する。
  • 第四引数を省略した場合は、単純に要素が取り除かれるだけになる。
  • 戻り値は、取り除いた要素が配列となって返される。

spliceRow:行の要素を取り除きつつ、新しい要素を追加する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
});

var ret = table.spliceRow(1, 1, 2, 'X', 'Y', 'Z');
console.log(ret);

handsontable.jpg

  • spliceCol の行版。

sort:カラムを指定してソートする

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    columnSorting: true,
    data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
});

table.sort(2, false);

handsontable.jpg

  • 第一引数に、ソートするカラムのインデックスを指定する。
  • 第二引数に、ソートの向きを指定する(true が昇順、 false が降順)。

updateSettings:オプションを更新する

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    colHeaders: true,
    colWidths: [100, 200]
});

document.getElementById('button').addEventListener('click', function() {
    table.updateSettings({
        colHeaders: ['one', 'two', 'three', 'four']
    });
});

handsontable.gif

  • コンストラクタで指定していたオプションを更新できる。
  • 既に設定済みのオプションは、特に明示しないかぎりそのままになる(例の場合 colWidths の設定は残ったままになっている)。

validateCells:全てのセルのバリデージョンを実行する

var grid = document.getElementById('grid');


var table = new Handsontable(grid, {
    data: [
        ['foo', 'hoge', 'bar']
    ],
    columns: [
        {type: 'numeric', data: 0},
        {type: 'text', data: 1},
        {type: 'date', data: 2},
    ]
});

document.getElementById('button').addEventListener('click', function() {
    table.validateCells();
});

handsontable.gif

  • プログラムでセルの値を設定した場合などはバリデーションが実行されていないことがあるので、そういう場合は validateCells() メソッドで明示的にバリデーションを実行できる。

undo, redo:アンドゥ・リドゥ

var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    undo: true
});

document.querySelector('#undo').addEventListener('click', function() {
    table.undo();
});

document.querySelector('#redo').addEventListener('click', function() {
    table.redo();
});

handsontable.gif

  • undo オプションを true にすることで、 undo(), redo() 関数が使えるようになる。

参考

47
47
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
47
47