3
4

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】スプレッドシートからInsert文を作成する手順

Posted at

この記事について

This is for 自分 as メモ

概要

A1セルにテーブル名を入れる。

2行目はカラム名を羅列。3行目以降はレコードとなる情報をセットする。

また、result シートを予め作成しておく。

スクリーンショット 2021-02-26 22.47.30.png

そのうえで、Google Apps Scriptを開いて下記を実行。

function makeInsertQuery() {

 let spreadSheetByActive = SpreadsheetApp.getActive();
 let sheetByActive = spreadSheetByActive.getActiveSheet();
 let range = sheetByActive.getRange(1,1,sheetByActive.getLastRow(), sheetByActive.getLastColumn());
 let headerRowIndex = 1;
 let firstValuesRowIndex = headerRowIndex + 1;
 let cells = range.getValues();
 let numRows = range.getNumRows();
 let numColumns = range.getNumColumns();
 let tableName = cells[0][0];
 let columnNames = [];

 for (var i = 0; i < numColumns; i++) {
  columnNames.push(cells[headerRowIndex][i]);
 }

 let prefix = "INSERT INTO " + tableName + " (" + columnNames.join(",") + ") VALUES (";

 let deleteTarget = spreadSheetByActive.getSheetByName('result');
 spreadSheetByActive.deleteSheet(deleteTarget)
 let newSheet = range.getSheet().getParent().insertSheet();
 newSheet.setName('result')

 let 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);
  }
}

結果。

スクリーンショット 2021-02-26 22.47.50.png

参考文献

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?