高级表格服务

通过高级 Google 表格服务,您可以使用 Apps 脚本访问 Google 表格 API。与 Apps 脚本的内置 Google Sheets API 服务非常相似,此 API 允许脚本读取、修改、设置格式和呈现 Google 表格中的数据。 在大多数情况下,内置服务更易于使用,但此高级服务提供了一些额外的功能。

参考

如需详细了解此服务,请参阅 Google Sheets API 的参考文档。与 Apps 脚本中的所有高级服务一样,高级 Google 表格服务使用的对象、方法和参数均与公共 API 相同。如需了解详情,请参阅方法签名是如何确定的

如需报告问题并查找其他支持,请参阅Google 表格支持指南

示例代码

以下示例代码使用 API 的版本 4;这是目前唯一可作为 Apps 脚本中的高级服务使用的 Google 表格 API 版本。

从范围中读取值

以下示例演示了如何使用 Google 表格高级服务从工作表中指定范围读取数据值。它相当于读取单个范围配方示例。

advanced/sheets.gs
/**
 * Read a range (A1:D5) of data values. Logs the values.
 * @param {string} spreadsheetId The spreadsheet ID to read from.
 * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
 */
function readRange(spreadsheetId = yourspreadsheetId) {
  try {
    const response = Sheets.Spreadsheets.Values.get(spreadsheetId, 'Sheet1!A1:D5');
    if (response.values) {
      console.log(response.values);
      return;
    }
    console.log('Failed to get range of values from spreadsheet');
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

将值写入多个范围

以下示例演示了如何通过一个请求将数据写入工作表中的不同不相交范围。它相当于写入多个范围配方示例。

advanced/sheets.gs
/**
 * Write to multiple, disjoint data ranges.
 * @param {string} spreadsheetId The spreadsheet ID to write to.
 * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate
 */
function writeToMultipleRanges(spreadsheetId = yourspreadsheetId) {
  // Specify some values to write to the sheet.
  const columnAValues = [
    ['Item', 'Wheel', 'Door', 'Engine']
  ];
  const rowValues = [
    ['Cost', 'Stocked', 'Ship Date'],
    ['$20.50', '4', '3/1/2016']
  ];

  const request = {
    'valueInputOption': 'USER_ENTERED',
    'data': [
      {
        'range': 'Sheet1!A1:A4',
        'majorDimension': 'COLUMNS',
        'values': columnAValues
      },
      {
        'range': 'Sheet1!B1:D2',
        'majorDimension': 'ROWS',
        'values': rowValues
      }
    ]
  };
  try {
    const response = Sheets.Spreadsheets.Values.batchUpdate(request, spreadsheetId);
    if (response) {
      console.log(response);
      return;
    }
    console.log('response null');
  } catch (e) {
    // TODO (developer) - Handle  exception
    console.log('Failed with error %s', e.message);
  }
}

添加新工作表

以下示例演示了如何创建具有特定大小和标签页颜色的新工作表。它等效于添加工作表配方示例。

advanced/sheets.gs
/**
 * Add a new sheet with some properties.
 * @param {string} spreadsheetId The spreadsheet ID.
 * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
 */
function addSheet(spreadsheetId = yourspreadsheetId) {
  const requests = [{
    'addSheet': {
      'properties': {
        'title': 'Deposits',
        'gridProperties': {
          'rowCount': 20,
          'columnCount': 12
        },
        'tabColor': {
          'red': 1.0,
          'green': 0.3,
          'blue': 0.4
        }
      }
    }
  }];
  try {
    const response =
      Sheets.Spreadsheets.batchUpdate({'requests': requests}, spreadsheetId);
    console.log('Created sheet with ID: ' +
      response.replies[0].addSheet.properties.sheetId);
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

创建数据透视表

以下示例演示了如何根据源数据创建透视表。 它等效于添加数据透视表配方示例。

advanced/sheets.gs
/**
 * Add a pivot table.
 * @param {string} spreadsheetId The spreadsheet ID to add the pivot table to.
 * @param {string} pivotSourceDataSheetId The sheet ID to get the data from.
 * @param {string} destinationSheetId The sheet ID to add the pivot table to.
 * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
 */
function addPivotTable(
    spreadsheetId = yourspreadsheetId,
    pivotSourceDataSheetId= yourpivotSourceDataSheetId,
    destinationSheetId= yourdestinationSheetId) {
  const requests = [{
    'updateCells': {
      'rows': {
        'values': [
          {
            'pivotTable': {
              'source': {
                'sheetId': pivotSourceDataSheetId,
                'startRowIndex': 0,
                'startColumnIndex': 0,
                'endRowIndex': 20,
                'endColumnIndex': 7
              },
              'rows': [
                {
                  'sourceColumnOffset': 0,
                  'showTotals': true,
                  'sortOrder': 'ASCENDING',
                  'valueBucket': {
                    'buckets': [
                      {
                        'stringValue': 'West'
                      }
                    ]
                  }
                },
                {
                  'sourceColumnOffset': 1,
                  'showTotals': true,
                  'sortOrder': 'DESCENDING',
                  'valueBucket': {}
                }
              ],
              'columns': [
                {
                  'sourceColumnOffset': 4,
                  'sortOrder': 'ASCENDING',
                  'showTotals': true,
                  'valueBucket': {}
                }
              ],
              'values': [
                {
                  'summarizeFunction': 'SUM',
                  'sourceColumnOffset': 3
                }
              ],
              'valueLayout': 'HORIZONTAL'
            }
          }
        ]
      },
      'start': {
        'sheetId': destinationSheetId,
        'rowIndex': 49,
        'columnIndex': 0
      },
      'fields': 'pivotTable'
    }
  }];
  try {
    const response = Sheets.Spreadsheets.batchUpdate({'requests': requests}, spreadsheetId);
    // The Pivot table will appear anchored to cell A50 of the destination sheet.
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}