创建数据透视表时出错

时间:2017-07-18 08:51:28

标签: google-apps-script google-sheets pivot-table google-sheets-api

我正在尝试使用Google Apps脚本创建数据透视表。下面的脚本运行后,没有输出,并显示错误:

  

ReferenceError:" Sheets"没有定义。 (第50行,文件"代码")



function createPivotTable() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  // The name of the sheet containing the data you want to put in a table.
  var sheetName = "Data";

  var pivotTableParams = {};
  
  // The source indicates the range of data you want to put in the table.
  // optional arguments: startRowIndex, startColumnIndex, endRowIndex, endColumnIndex
  pivotTableParams.source = {
    sheetId: ss.getSheetByName(sheetName).getSheetId()
  };
  
  // Group rows, the 'sourceColumnOffset' corresponds to the column number in the source range
  // eg: 0 to group by the first column
  pivotTableParams.rows = [{
    sourceColumnOffset: 2,
    sortOrder: "ASCENDING"
  }];
  
  // Defines how a value in a pivot table should be calculated.
  pivotTableParams.values = [{
    summarizeFunction: "COUNTA",
    sourceColumnOffset: 2
  }];
    
  // Create a new sheet which will contain our Pivot Table
  var pivotTableSheet = ss.insertSheet();
  var pivotTableSheetId = pivotTableSheet.getSheetId();
  
  // Add Pivot Table to new sheet
  // Meaning we send an 'updateCells' request to the Sheets API
  // Specifying via 'start' the sheet where we want to place our Pivot Table
  // And in 'rows' the parameters of our Pivot Table
  var request = {
    "updateCells": {
      "rows": {
        "values": [{
          "pivotTable": pivotTableParams
        }]
      },
      "start": {
        "sheetId": pivotTableSheetId
      },
      "fields": "pivotTable"
    }
  };

  Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId());
}




1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。我错过了Google表格API https://developers.google.com/sheets/api/quickstart/apps-script

启用后,脚本终于有效了。

相关问题