スプレッドシートへPOSTする
管理者
|
2023年02月15日
スプレッドシートへPOSTをする場合にスプレッドシートの拡張機能でApp Scriptをプログラムする。
下記内容で、タブ名(A)はシート下部にあるタブの名前で必ず1つは存在しています。
タブが複数ある場合にタブ名ごとにデータをセットできます。
POSTのキー名はPOSTされた実際にキー名を書き、キー名の順番にスプレッドシート列(A、B、C・・・)にセットされます。
PHPサイド
$google_url = "グーグルスプレッドシートWebアプリURL";
$form_data = [
"sheetname" => "スプレッドシートタブ名A",
"POSTキー名A" => "2022-02-01",
"POSTキー名B" => "山田太郎"
];
$context = [
'http' => [
"method" => "POST",
"header" => implode("\r\n", ["Content-Type: application/x-www-form-urlencoded",]),
"content" => http_build_query($form_data)
]
];
$response_json = file_get_contents($google_url, false, stream_context_create($context));
App Scriptサイド
function doPost(e){
var sheetname = e.parameter.sheetname;
var spread = SpreadsheetApp.getActiveSpreadsheet();
var lastRow = spread.getSheetByName(sheetname).getLastRow();
var jsonData =
var data = {
"タブ名(A)": [
"POSTのキー名1",
"POSTのキー名2"
],
"タブ名(B)": [
"POSTのキー名1",
"POSTのキー名2"
],
}
if(data[sheetname] != undefined){
data[sheetname].forEach(function(col, i){
spread.getSheetByName(sheetname).getRange((lastRow + 1), (i + 1)).setValue(e.parameter[col]);
jsonData[col] = e.parameter[col];
});
return ContentService.createTextOutput(JSON.stringify(jsonData)).setMimeType(ContentService.MimeType.JSON);
}
}