简体   繁体   中英

Create EmbeddedChart in Google Sheets without using Range, with Google Apps Script

I'm trying to create an EmbeddedChart in Google Sheets without using Range in my spreadsheet, but using my own values that I've calculated. After searching for hours, I'm not finding the solution. What is the best way to do this ? (To sump up I want to use the EmbeddedChartBuilder class like the ChartBuilder class)

  • You want to create a chart with clickable using Charts Service and put to the Spreadsheet.
  • You want to achieve this using Google Apps Script.

I could understand like above. If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

In this answer, I used the script of your previous question by modifying a little. In this case, in your script, the values from the column "C2:C" are retrieved and the chart is created using the values and duplicated numbers of the values.

Pattern 1:

In this pattern, in order to create the chart with clickable, the chart is created by Google Visualization API and put to a dialog on Spreadsheet.

Usage:

In order to run the script, please run the function of openDialog() at the script editor after copied and pasted the following scripts. By this, a dialog is opened to the Spreadsheet and the chart is put to the dialog.

In this sample script, the values are retrieved from the column "C" of the sheet of const sheetName = "Sheet1" in the Spreadsheet. So please use the container-bound script of Spreadsheet. Please be careful this.

Sample script: Code.gs (Google Apps Script side)

const sheetName = "Sheet1";  // Please set the sheet name.

// Please run this function.
function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index').setWidth(650).setHeight(550);
  SpreadsheetApp.getUi().showModalDialog(html, "sample");
}

function getValuesFromSpreadsheet() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  return sheet.getRange(`C2:C${sheet.getLastRow()}`).getValues()
    .reduce((o, [e]) => {
      o[e] = e in o ? o[e] + 1 : 1
      return o;
    }, {});
}

Sample script: index.html (HTML&Javascript side)

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
  google.charts.load('current', {'packages':['corechart', 'bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    google.script.run.withSuccessHandler(artists => {
      var dataArtists = new google.visualization.DataTable();
      dataArtists.addColumn('string', 'Artists');
      dataArtists.addColumn('number', 'Count');
      for(var key in artists) {
        dataArtists.addRow([key, artists[key]]);
      }
      const options = {
        title: 'Number of Tracks per Artist',
        vAxis: {title: "Artists"},
        hAxis: {title: "Number of  Tracks"},
        width: 600,
        height: 500
      };
      barsVisualization = new google.visualization.BarChart(document.getElementById('chart_div'));
      barsVisualization.draw(dataArtists, options);
    }).getValuesFromSpreadsheet();
  }
</script>

Pattern 2:

In this pattern, the chart created with the modified script of your script is put to the Spreadsheet as an image. In this case, the chart is put by running the function of myFunction created with Charts Service . In this case, the data is retrieved from the active sheet. Please be careful this.

Sample script:

function myFunction() {
  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var artistsArray;
  var dataArtists;
  dataArtists = Charts.newDataTable().addColumn(Charts.ColumnType.STRING, 'Artists').addColumn(Charts.ColumnType.NUMBER, 'Count');
  var artists = sheet.getRange(`C2:C${sheet.getLastRow()}`).getValues()
    .reduce((o, [e]) => {
      o[e] = e in o ? o[e] + 1 : 1
      return o;
    }, {});
  for(var key in artists) {
    dataArtists.addRow([key, artists[key]]);
  }
  dataArtists.build();
  var artistsChart = Charts.newBarChart()
  .setDataTable(dataArtists)
  .setTitle('Number of Tracks per Artist')
  .setXAxisTitle('Number of  Tracks')
  .setYAxisTitle('Artists')
  .setDimensions(600, 500)
  .build();
  sheet.insertImage(artistsChart.getBlob(), 1, 1);
}

Note:

  • In this case, please enable V8 at the script editor.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM