Dịch vụ Trang tính nâng cao

Dịch vụ Trang tính nâng cao cho phép bạn truy cập vào API Trang tính bằng Apps Script. Giống như dịch vụ API Google Trang tính tích hợp sẵn của Apps Script, API này cho phép tập lệnh đọc, chỉnh sửa, định dạng và trình bày dữ liệu trong Google Trang tính. Trong hầu hết các trường hợp, dịch vụ tích hợp sẵn sẽ dễ sử dụng hơn, nhưng dịch vụ nâng cao này cung cấp thêm một số tính năng.

Tài liệu tham khảo

Để biết thông tin chi tiết về dịch vụ này, hãy xem tài liệu tham khảo về API Trang tính. Giống như tất cả các dịch vụ nâng cao trong Apps Script, dịch vụ Trang tính nâng cao sử dụng cùng đối tượng, phương thức và tham số như API công khai. Để biết thêm thông tin, hãy xem phần Cách xác định chữ ký phương thức.

Để báo cáo sự cố và tìm dịch vụ hỗ trợ khác, hãy xem Hướng dẫn hỗ trợ Trang tính.

Mã mẫu

Mã mẫu bên dưới sử dụng phiên bản 4 của API; đây là phiên bản duy nhất của API Trang tính hiện có sẵn dưới dạng dịch vụ nâng cao trong Apps Script.

Đọc các giá trị trong một dải ô

Ví dụ sau minh hoạ cách đọc các giá trị dữ liệu từ một dải ô được chỉ định trong một trang tính bằng dịch vụ nâng cao của Trang tính. Mẫu này tương đương với mẫu công thức Đọc một dải ô.

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);
  }
}

Ghi giá trị vào nhiều dải ô

Ví dụ sau minh hoạ cách ghi dữ liệu vào nhiều phạm vi không phân tách trong một trang tính chỉ có một yêu cầu. Công thức này tương đương với mẫu công thức Ghi vào nhiều dải ô.

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);
  }
}

Thêm trang tính mới

Ví dụ sau minh hoạ cách tạo trang tính mới bằng kích thước và màu thẻ cụ thể. Tệp này tương đương với mẫu công thức nấu ăn Thêm trang tính.

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);
  }
}

Tạo bảng tổng hợp

Ví dụ sau đây minh hoạ cách tạo bảng tổng hợp từ dữ liệu nguồn. Công thức này tương đương với mẫu công thức Thêm bảng tổng hợp.

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);
  }
}