スプレッドシートの内容からjsonデータを生成する方法を試してみました。
設定方法
例として、以下のようなスプレッドシートを用意します。
拡張機能 > Apps Script を選択します。
コード.gsの内容を下記に変更します。
function generateJson() {
const jsonKey = 'data'; // jsonのkey名
// データの取得
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const lastRow = sheet.getLastRow();
const lastColum = sheet.getLastColumn();
const keys = sheet.getSheetValues(1, 1, 1, lastColum).flat();
const values = sheet.getSheetValues(2, 1, (lastRow-1), lastColum);
// データの整形
const data = values.reduce((data, currentValue) => {
const d = keys.reduce((previousValue, currentKey, index) => {
previousValue[currentKey] = currentValue[index];
return previousValue;
}, {});
data[jsonKey].push(d);
return data;
}, {[jsonKey]: []});
const json = JSON.stringify(data);
return json;
}
function downloadDialog() {
const html = HtmlService.createTemplateFromFile("dialog").evaluate();
SpreadsheetApp.getUi().showModalDialog(html, 'json形式でダウンロード');
}
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('json')
.addItem('json形式でダウンロード', 'downloadDialog')
.addToUi();
};
次にHTMLファイルを追加します。
dialog.htmlというファイル名にして、以下の内容にします。
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button onclick="dl()">ダウンロードが始まらない場合はクリック</button>
<script type='text/javascript'>
function dl() {
const json = <?= generateJson(); ?>;
const blob = new Blob([json], {
"type" : "application/json"
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'data.json';
link.click();
}
dl();
</script>
</body>
</html>
スプレッドシートに戻ってリロードすると、上部メニューにjsonという項目が追加されます。
json > json形式でダウンロードを選択します。
以下のようなダイアログが表示され、data.jsonというファイル名で以下の内容でダウンロードできました。
{"data":[{"id":1,"name":"asakura","age":17},{"id":2,"name":"higuchi","age":17},{"id":3,"name":"ichikawa","age":15},{"id":4,"name":"fukumaru","age":16}]}
色々と試してみましたが、GAS側でファイルのダウンロードまで完結できなさそうだったので、HTMLファイルを用意してスプレッドシート側で呼び出す形での対応になりました。






コメントが承認されるまで時間がかかります。