ドキュメントの作成と管理

この 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 ドライブ フォルダを操作する

ドキュメント API を使用して、指定したドライブ フォルダ内に直接ドキュメントを作成するオプションはありません。デフォルトでは、作成されたドキュメントはドライブのユーザーのルートフォルダに保存されます。

ただし、ファイルをドライブ フォルダに保存する方法は 2 つあります。

どちらの方法でも、適切な Drive API スコープを追加して呼び出しを承認する必要があります。ドライブのスコープの詳細については、Google Drive API スコープを選択するをご覧ください。

共有ドライブ フォルダ内でファイルを移動または作成するには、共有ドライブのサポートを実装するをご覧ください。

既存のドキュメントをコピーする

ドキュメントをコピーするには、Drive API の files.copy メソッドを使用します。

次のコードサンプルは、既存のドキュメントをコピーする方法を示しています。Drive API 呼び出しに使用する ID は、ドキュメントの URL で確認できます。詳しくは、ドキュメント 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 スコープを選択するをご覧ください。