16
12

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 5 years have passed since last update.

GoogleスプレッドシートからINSERT文を生成するGoogle Apps Script

Last updated at Posted at 2016-06-21

GoogleスプレッドシートからINSERT文を生成するGoogle Apps Scriptのメモ。

以下のように表を選択した状態で

スクリーンショット 2016-06-21 21.20.51.png

実行すると、こんな感じにINSERT文を別シートに生成するGoogle Apps Scriptです。

スクリーンショット 2016-06-21 21.21.13.png

コードは以下の通り。

function create_insert() {
  var headerRowIndex = 1;
  var firstValuesRowIndex = headerRowIndex + 1;
  var range = SpreadsheetApp.getActiveRange();
  var cells = range.getValues();
  var numRows = range.getNumRows();
  var numColumns = range.getNumColumns();

  var tableName = cells[0][0];

  var columnNames = [];
  for (var i = 0; i < numColumns; i++) {
    columnNames.push(cells[headerRowIndex][i]);
  }
  var prefix = "INSERT INTO " + tableName + " (" + columnNames.join(",") + ") VALUES (";

  var newSheet = range.getSheet().getParent().insertSheet();
  var targetCell = newSheet.getActiveCell();
  for (var i = firstValuesRowIndex; i < numRows; i++) {
    var values = [];
    for (var j = 0; j < numColumns; j++) {
      values.push(cells[i][j]);
    }
    targetCell.setValue(prefix + values.join(",") + "); ");
    targetCell = targetCell.offset(1, 0);
  }
}
16
12
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
16
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?