TypeError:无法调用未定义的方法“ insertChart”

时间:2019-07-01 10:38:06

标签: google-apps-script google-sheets

我正在尝试将嵌入的图表插入到Google表格中进行数据分析。但是,当我运行代码时,它将引发以下错误:

  

TypeError:无法调用未定义的方法“ insertChart”(第87行,文件“ Code”)。

这是我创建图表的功能:

function createBarGraph(activeSheet) {

var chart = activeSheet.insertChart()
chart.newChart()
.setChartType(Charts.ChartType.COLUMN)
.setOption('Chart Title', 'Service reviews')
.setPosition(5,5,0,0)
.build();
}

activeSheet是另一个函数中包含的变量,该函数为每个月创建一个新工作表。需要在该工作表中创建嵌入式图表,以正确反映每个月的数据。我注意到我没有添加SpreadsheetApp.getActiveSpreadSheet,这是基于这样的假设,因为在另一个函数中调用了此函数,因此此处不需要。

我要去哪里错了?

这是调用此函数的代码。

function checkSheetName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = formatDate(); // load the current 'Month-Year'
var activeSheet;

try {
activeSheet = ss.getSheetByName(sheetName);
ss.setActiveSheet(activeSheet); // try to set 'sheetName' as active sheet
} catch (e) { // if returns error,
activeSheet = createNewMonthSheet(); // creates a new sheet 
} 
return activeSheet;
}

function createNewMonthSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = formatDate(); // load the current 'Month-Year'
ss.insertSheet(sheetName, 2); // creates a new sheet on the left side, after 2   existing sheets
var newSheet = ss.getSheetByName(sheetName);
var columns = ['Comment','Compliment','Complaint']; // Array of review type.
var rows = ['Befriending','Finance','Fund Raising','Home Help','I & A','Mgmt 
Services','Toes Nails','Trading']; // Array of services provided.
          for(r=0; r<rows.length; r++){
          newSheet.getRange(r+2, 1).setValue(rows[r]);} // iterates through 
the length of row array, gets the range and sets the value.
for(c=0; c<columns.length; c++)
{
  newSheet.getRange(1, c+2).setValue(columns[c]); // iterates through length of column array, gets the range and sets the value.
}
  return ss.getSheetByName(sheetName); //returns active spreadsheet with date formated M & YYYY.
}

function formatDate() {
var monthNames = 
["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var monthNumber = Utilities.formatDate(new Date(), 'GMT+12:00', "M");
var yearNumber = Utilities.formatDate(new Date(), 'GMT+12:00', "yyyy");
return monthNames[monthNumber-1]+'-'+yearNumber; 

}

1 个答案:

答案 0 :(得分:0)

根据insertChart()的{​​{3}},您必须在构建后调用它,而在构建图表之前要调用insertChart()

尝试这样编写函数:

function createBarGraph(activeSheet) {

var chart = chart.newChart()
.setChartType(Charts.ChartType.COLUMN)
.setOption('Chart Title', 'Service reviews')
.setPosition(5,5,0,0)
.build();

activeSheet.insertChart()

}