创建和管理文档

此 Google 文档 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 云端硬盘文件夹

您无法通过 Google 文档 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 范围