Search code examples
google-sheetsgoogle-apps-scriptcharts

Google Apps Script - Can I modify one option of an embedded chart and preserve the other options?


I am trying to create a function (ultimately a menu button) that automatically resizes all the charts in a Sheet to a defined render width. I want to keep the other chart options (which might have changed from their default values before running this function) intact.

My code so far:

function resizeCharts() {
  var newWidth = 1000;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var currentSheet = ss.getActiveSheet();
  var sheetCharts = currentSheet.getCharts();

  for (var i = 0; i < sheetCharts.length; i++) {
    var modifiedChart = sheetCharts[i].modify();
    modifiedChart = modifiedChart.setOption('width', newWidth).build();
    currentSheet.updateChart(modifiedChart);
  }
}

This code will adjust the width of the chart, but it changes the other options (e.g. series colors, axis formats), which I don't want.

Is there a way to preserve all the existing options of a chart except for the one I want to change?


Solution

  • In case you just need to update chart's size or position, there is Advanced Sheets Service and specific UpdateEmbeddedObjectPosition request for that (which is not available via built-in Spreadsheet Service).

    Example:

    // your spreadsheet id
    let ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
    
    // get all charts from sheet (replace 'YOUR_SHEET_TITLE')
    let charts = Sheets.Spreadsheets
      .get(ssId)
      .sheets
      .filter(sheet => sheet.properties.title === 'YOUR_SHEET_TITLE')[0]
      .charts;
    
    // array of requests
    let requests = [];
    
    // loop charts array
    charts.forEach(chart => {
    
      // create request for each chart
      let request = {
        updateEmbeddedObjectPosition: {
          objectId: chart.chartId,
          newPosition: {
            overlayPosition: {
              widthPixels: 1000 // specify your width
            }
          },
          fields: 'widthPixels' // list fields you want to update
        }
      };
        
      // push request to array
      requests.push(request);
    
    });
    
    
    // send requests at once
    // this may allow to improve script performance
    Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
    

    References: