Tạo và quản lý bảng tính

Tài liệu này giải thích cách tạo và quản lý bảng tính trong Google Trang tính bằng API Google Trang tính.

Tạo bảng tính

Để tạo tệp trong Trang tính, hãy sử dụng phương thức create trên tài nguyên spreadsheets mà không có tham số.

Khi bạn tạo tệp, phương thức này sẽ trả về một tài nguyên spreadsheets. Tài nguyên được trả về chứa spreadsheetId, properties, danh sách sheetsspreadsheetUrl.

Mã mẫu sau đây cho thấy cách tạo một bảng tính trống có tiêu đề được chỉ định.

Apps Script

sheets/api/spreadsheet_snippets.gs
/**
 * Creates a new sheet using the sheets advanced services
 * @param {string} title the name of the sheet to be created
 * @returns {string} the spreadsheet ID
 */
Snippets.prototype.create = (title) => {
  // This code uses the Sheets Advanced Service, but for most use cases
  // the built-in method SpreadsheetApp.create() is more appropriate.
  try {
    const sheet = Sheets.newSpreadsheet();
    sheet.properties = Sheets.newSpreadsheetProperties();
    sheet.properties.title = title;
    const spreadsheet = Sheets.Spreadsheets.create(sheet);

    return spreadsheet.spreadsheetId;
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log("Failed with error %s", err.message);
  }
};

Java

sheets/snippets/src/main/java/Create.java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.Spreadsheet;
import com.google.api.services.sheets.v4.model.SpreadsheetProperties;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

/* Class to demonstrate the use of Spreadsheet Create API */
public class Create {
  /**
   * Create a new spreadsheet.
   *
   * @param title - the name of the sheet to be created.
   * @return newly created spreadsheet id
   * @throws IOException - if credentials file not found.
   */
  public static String createSpreadsheet(String title) throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Create the sheets API client
    Sheets service = new Sheets.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Sheets samples")
        .build();

    // Create new spreadsheet with a title
    Spreadsheet spreadsheet = new Spreadsheet()
        .setProperties(new SpreadsheetProperties()
            .setTitle(title));
    spreadsheet = service.spreadsheets().create(spreadsheet)
        .setFields("spreadsheetId")
        .execute();
    // Prints the new spreadsheet id
    System.out.println("Spreadsheet ID: " + spreadsheet.getSpreadsheetId());
    return spreadsheet.getSpreadsheetId();
  }
}

JavaScript

sheets/snippets/sheets_create.js
function create(title, callback) {
  try {
    gapi.client.sheets.spreadsheets.create({
      properties: {
        title: title,
      },
    }).then((response) => {
      if (callback) callback(response);
      console.log('Spreadsheet ID: ' + response.result.spreadsheetId);
    });
  } catch (err) {
    document.getElementById('content').innerText = err.message;
    return;
  }
}

Node.js

sheets/snippets/sheets_create.js
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Creates a new Google Spreadsheet.
 * @param {string} title The title of the new spreadsheet.
 * @return {string} The ID of the created spreadsheet.
 */
async function create(title) {
  // Authenticate with Google and get an authorized client.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  // Create a new Sheets API client.
  const service = google.sheets({version: 'v4', auth});

  // The resource body for creating a new spreadsheet.
  const resource = {
    properties: {
      title,
    },
  };

  // Create the new spreadsheet.
  const spreadsheet = await service.spreadsheets.create({
    resource,
    fields: 'spreadsheetId',
  });

  // Log the ID of the new spreadsheet.
  console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`);
  return spreadsheet.data.spreadsheetId;
}

PHP

sheets/snippets/src/SpreadsheetCreate.php
<?php
use Google\Client;
use Google\Service\Drive;
use Google\Service\Sheets\SpreadSheet;

/**
* create an empty spreadsheet
* 
*/

 function create($title)
    {   
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
        $client = new Google\Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Google\Service\Drive::DRIVE);
        $service = new Google_Service_Sheets($client);
        try{

            $spreadsheet = new Google_Service_Sheets_Spreadsheet([
                'properties' => [
                    'title' => $title
                    ]
                ]);
                $spreadsheet = $service->spreadsheets->create($spreadsheet, [
                    'fields' => 'spreadsheetId'
                ]);
                printf("Spreadsheet ID: %s\n", $spreadsheet->spreadsheetId);
                return $spreadsheet->spreadsheetId;
        }
        catch(Exception $e) {
            // TODO(developer) - handle error appropriately
            echo 'Message: ' .$e->getMessage();
          }
    }

Python

sheets/snippets/sheets_create.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def create(title):
  """
  Creates the Sheet the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  try:
    service = build("sheets", "v4", credentials=creds)
    spreadsheet = {"properties": {"title": title}}
    spreadsheet = (
        service.spreadsheets()
        .create(body=spreadsheet, fields="spreadsheetId")
        .execute()
    )
    print(f"Spreadsheet ID: {(spreadsheet.get('spreadsheetId'))}")
    return spreadsheet.get("spreadsheetId")
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  # Pass: title
  create("mysheet1")

Ruby

sheets/snippets/lib/spreadsheet_snippets.rb
spreadsheet = {
  properties: {
    title: 'Sales Report'
  }
}
spreadsheet = service.create_spreadsheet(spreadsheet,
                                         fields: 'spreadsheetId')
puts "Spreadsheet ID: #{spreadsheet.spreadsheet_id}"

Sắp xếp bảng tính trong thư mục Google Drive

Theo mặc định, bảng tính đã tạo được lưu vào thư mục gốc của người dùng trên Google Drive.

Nếu bạn muốn lưu bảng tính vào một thư mục Drive được chỉ định, hãy sử dụng các phương thức sau:

Đối với một trong hai lựa chọn thay thế, bạn cần thêm các phạm vi Drive API thích hợp để uỷ quyền cho lệnh gọi.

Nếu ứng dụng của bạn đang sử dụng Tài khoản dịch vụ, thì Tài khoản dịch vụ sẽ sở hữu bảng tính đã tạo. Sau đó, tệp này sẽ nằm trong bộ nhớ Drive dành riêng của Tài khoản dịch vụ. Tệp không xuất hiện trong các tài khoản bộ nhớ Drive khác, trừ phi được chia sẻ rõ ràng. Để biết thêm thông tin, hãy xem bài viết Quyền sở hữu tệp.

Để di chuyển hoặc tạo tệp trong thư mục bộ nhớ dùng chung, hãy tham khảo bài viết Triển khai tính năng hỗ trợ bộ nhớ dùng chung.

Để tìm hiểu thêm về giới hạn ô và hàng trong Google Trang tính, hãy xem bài viết Các tệp bạn có thể lưu trữ trong Google Drive.

Lấy bảng tính

Để lấy bảng tính, hãy sử dụng phương thức get trên tài nguyên spreadsheets với tham số đường dẫn spreadsheetId.

Phương thức này trả về tệp dưới dạng thực thể của tài nguyên spreadsheets. Theo mặc định, dữ liệu trong bảng tính sẽ không được trả về. Tài nguyên được trả về chứa cấu trúc và siêu dữ liệu của bảng tính, bao gồm cả các thuộc tính của bảng tính (chẳng hạn như tiêu đề, ngôn ngữ và múi giờ) và một số thông tin chi tiết về trang tính (chẳng hạn như định dạng và phạm vi được bảo vệ).

Để đưa dữ liệu vào tài nguyên spreadsheets, hãy sử dụng 2 phương thức sau:

Khi làm việc với các bảng tính lớn, bạn nên chỉ truy vấn các trường bảng tính cụ thể mà bạn cần. Phương thức get trả về tất cả dữ liệu được liên kết với bảng tính, vì vậy, các truy vấn chung cho bảng tính lớn có thể diễn ra chậm. Ví dụ: để đọc số 100 từ một ô, spreadsheets.get sẽ trả về giá trị ô cùng với siêu dữ liệu (chẳng hạn như tên phông chữ, kích thước, v.v.) dẫn đến tải trọng JSON lớn và chậm phân tích cú pháp. Ngược lại, một lệnh gọi tương tự đến values.get chỉ trả về giá trị ô cụ thể, dẫn đến phản hồi nhanh hơn và nhẹ hơn nhiều.

Để biết thêm thông tin về tài nguyên spreadsheets.values, bao gồm spreadsheets.values.getspreadsheets.values.batchGet, hãy xem các tài liệu sau:

Liệt kê bảng tính

API Trang tính không cung cấp phương thức để liệt kê bảng tính cho người dùng đã xác thực.

Để truy xuất danh sách bảng tính, bạn có thể sử dụng phương thức list của Drive API trên tài nguyên files, chỉ định application/vnd.google-apps.spreadsheet làm mimeType:

HTTP

GET https://www.googleapis.com/drive/v3/files?q=mimeType='application/vnd.google-apps.spreadsheet'

cURL

curl -X GET "https://www.googleapis.com/drive/v3/files?q=mimeType='application/vnd.google-apps.spreadsheet'" \
 -H "Authorization: Bearer ACCESS_TOKEN" \
 -H "Accept: application/json"

Thay thế ACCESS_TOKEN bằng mã truy cập cấp quyền truy cập vào API.

Việc sử dụng phương thức files.list để liệt kê bảng tính của người dùng yêu cầu một phạm vi API Drive bị hạn chế.

Sau đây là một vài bước tiếp theo mà bạn có thể thử: