建立及管理文件

這個 Google Document 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 雲端硬碟資料夾

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

不過,有兩種方法可將檔案儲存至雲端硬碟資料夾:

無論採用哪一種替代方案,您都需要新增適當的 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 範圍」。