建立及管理文件

這個 Google Docs API 頁面說明如何執行涉及 Google 文件文件的特定高階工作,例如:

  • 建立文件
  • 複製現有文件

以下段落將詳細說明這些工作。

建立空白文件

如要建立文件,請在 documents 集合上使用 documents.create 方法。

以下程式碼範例說明如何建立具有指定標題的空白文件:

Java

private static void createDoc(Docs service) throws IOException {     Document doc = new Document()             .setTitle("My Document");     doc = service.documents().create(doc)             .execute();     System.out.println("Created document with title: " + doc.getTitle()); }

PHP

$title = 'My Document'; $document = new Google_Service_Docs_Document(array(     'title' => $title ));  $document = $service->documents->create($document); printf("Created document with title: %s\n", $document->title);

Python

title = 'My Document' body = {     'title': title } doc = service.documents() \     .create(body=body).execute() print('Created document with title: {0}'.format(     doc.get('title')))

使用 Google 雲端硬碟資料夾

您無法使用 Docs API 直接在指定的 Google 雲端硬碟資料夾中建立文件。根據預設,建立的文件會儲存至使用者在雲端硬碟中的根資料夾。

不過,您可以透過兩種方式將檔案儲存至雲端硬碟資料夾:

無論選擇哪種方法,都必須新增適當的 Drive API 範圍,才能授權呼叫。如要進一步瞭解雲端硬碟範圍,請參閱「選擇 Google Drive API 範圍」。

如要在共用雲端硬碟資料夾中移動或建立檔案,請參閱「實作共用雲端硬碟支援功能」。

複製現有文件

如要複製文件,請使用 Drive API 的 files.copy 方法。

以下程式碼範例說明如何複製現有文件。您可以在文件網址中找到要用於 Drive API 呼叫的 ID。詳情請參閱「文件 ID」。

https://docs.google.com/document/d/DOCUMENT_ID/edit 

Java

String copyTitle = "Copy Title"; File copyMetadata = new File().setName(copyTitle); File documentCopyFile =         driveService.files().copy(documentId, copyMetadata).execute(); String documentCopyId = documentCopyFile.getId();

Node.js

var copyTitle = "Copy Title"; let request = {   name: copyTitle, }; this.driveService.files.copy({   fileId: documentId,   resource: request, }, (err, driveResponse) => {   let documentCopyId = driveResponse.id; });

PHP

<?php $copyTitle = 'Copy Title'; $copy = new Google_Service_Drive_DriveFile(array(     'name' => $copyTitle )); $driveResponse = $driveService->files->copy($documentId, $copy); $documentCopyId = $driveResponse->id;

Python

copy_title = 'Copy Title' body = {     'name': copy_title } drive_response = drive_service.files().copy(     fileId=document_id, body=body).execute() document_copy_id = drive_response.get('id')

請注意,您必須使用適當的 Drive API 範圍授權呼叫。如要進一步瞭解雲端硬碟範圍,請參閱「選擇 Google Drive API 範圍」。