0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GASのから送った値を使ってスプレットシートで折れ線グラフを作成する

Last updated at Posted at 2025-01-11

概要

GASから送った値を使いスプレットシートで折れ線グラフを生成する方法を簡単にまとめる。

前提

下記の内容が完了していること。

方法

  1. GASのコードを下記の様に書き換える

    function makeGraph() {
      // スプレッドシートIDを指定
      const spreadsheetId = 'スプレットシートのID';
    
      // スプレッドシートを開く
      let sheet = SpreadsheetApp.openById(spreadsheetId).getActiveSheet();
    
      const min = 0;
      const max = 31;
      const value = getRandomInt(min, max);
    
      // スプレッドシートに追加
      sheet.appendRow([new Date(), value]);
    
      // データ範囲を指定
      let lastRow = sheet.getLastRow();
      let dataRange = sheet.getRange('A1:B' + lastRow);
    
      // 既存のグラフを取得
      let charts = sheet.getCharts();
      if (charts.length > 0) {
        // 既存のグラフがある場合は更新
        let chart = charts[0].modify()
          .clearRanges()
          .addRange(dataRange)
          .build();
        sheet.updateChart(chart);
      } else {
        // グラフがない場合は新規作成
        let newChart = sheet.newChart()
          .setChartType(Charts.ChartType.LINE)
          .addRange(dataRange)
          .setPosition(5, 5, 0, 0)  // グラフの位置を指定
          .setOption('title', 'Sample Line Chart')
          .build();
        sheet.insertChart(newChart);
      }
    }
    
    function getRandomInt(min, max) {
      const minCeiled = Math.ceil(min);
      const maxFloored = Math.floor(max);
      return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled);
    }
    
  2. 一旦当該のスプレットシートのデータを削除

  3. GASのコードを実行

  4. A列B列にデータが追加されてグラフが作図される(何度か実行した例↓)

    CleanShot 2025-01-11 at 11.27.17@2x.png

参考文献

getActiveSheet()について↓

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?