如何使用“chart.getOptions()”检索信息?

问题描述 投票:0回答:1

我目前在谷歌工作表中有一个标题为“当前强度”的图表。 Image of chart in the worksheet ,我需要使用 Google App Script 验证它是否有标题、正确的数据以及 x 轴和 y 轴标题。

我想使用 Google App 脚本检索有关图表的信息,特别是标题、X 和 Y 轴标题,以及数据的来源(图表的范围/系列)。

我尝试过使用

chart.GetOptions()
,但是每当我在方法中输入字符串作为参数时,它总是返回一个
Error

Exception: The parameters (String) don't match the method signature for SpreadsheetApp.EmbeddedChart.getOptions.

当我输入

chart.GetOptions('title')
时抛出了上面的错误,这应该根据ChatGPT工作(我也一直在尝试ChatGPT,但我认为它可能已经过时了,因为训练数据仅限于2021年9月)。

这是我当前的源代码:

function Check_Bar_Chart() {
  var charts = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Present Strength").getCharts();
  
  if (charts.length == 0) {
    SpreadsheetApp.getUi().alert("Where is your bar chart...?");
    return false;
  } 

  var chart = charts[0];
  Logger.log(chart.getOptions('title'));
}

代码识别出存在图表,当图表不存在时,

charts.length == 0
返回
True
。但是,我无法让它继续工作。

这让我回到了我的问题:如何使用 Google App 脚本检索标题、X 和 Y 轴标题以及数据的来源(图表的范围/系列)?

google-apps-script google-sheets google-visualization
1个回答
0
投票

修改要点:

  • 从你的脚本来看,我认为类 Chart 的 getOptions() 方法没有参数。这种情况下就需要使用ChartOptions类的get(option)方法了。

当这反映在您的脚本中时,以下修改如何?

修改后的脚本:

function Check_Bar_Chart() {
  var charts = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Present Strength").getCharts();

  if (charts.length == 0) {
    SpreadsheetApp.getUi().alert("Where is your bar chart...?");
    return false;
  }

  var chart = charts[0];
  var options = chart.getOptions();

  Logger.log(options.get('title')); // Chart title
  Logger.log(options.get('hAxis.title')); // X-axis title
  Logger.log(options.get('vAxes.0.title')); // Y-axis title

  var ranges = chart.getRanges().map(r => `'${r.getSheet().getSheetName()}'!${r.getA1Notation()}`);
  Logger.log(ranges);
}
  • 通过此修改,检索图表标题、X 轴标题和 Y 轴标题。而且,还可以检索源范围。

  • 在这种情况下,

    chart.getRanges()
    返回源范围对象。

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.