创建电子表格

本页介绍了如何创建电子表格。

示例

如需创建电子表格,请对 spreadsheets 集合使用 create 方法,如以下示例所示。

此示例会创建一个具有指定标题的空白电子表格。

Apps 脚本

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 {
    let 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
/**
 * Create a google spreadsheet
 * @param {string} title Spreadsheets title
 * @return {string} Created spreadsheets ID
 */
async function create(title) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  const service = google.sheets({version: 'v4', auth});
  const resource = {
    properties: {
      title,
    },
  };
  try {
    const spreadsheet = await service.spreadsheets.create({
      resource,
      fields: 'spreadsheetId',
    });
    console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`);
    return spreadsheet.data.spreadsheetId;
  } catch (err) {
    // TODO (developer) - Handle exception
    throw err;
  }
}

PHP

sheets/snippets/src/SpreadsheetCreate.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}"

处理 Google 云端硬盘文件夹

您无法使用 Google 表格 API 直接在指定的云端硬盘文件夹中创建电子表格。默认情况下,系统会将创建的电子表格保存到用户云端硬盘的根文件夹中。

不过,您可以通过以下 2 种方式将文件保存到云端硬盘文件夹:

对于这两种方法,您都需要添加适当的 Drive API 权限范围才能授权调用。

如需在共享云端硬盘文件夹中移动或创建文件,请参阅实现共享云端硬盘支持

如需详细了解 Google 表格中的单元格和行数限制,请参阅可存储在 Google 云端硬盘中的文件