拡張ドキュメント サービス
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
高度なドキュメント サービスを使用すると、Apps Script で Google Docs API を使用できます。Apps Script の組み込み Docs サービスと同様に、この API を使用すると、スクリプトで Google ドキュメントのコンテンツの読み取り、編集、フォーマットを行うことができます。ほとんどの場合、組み込みサービスの方が使いやすいですが、この拡張サービスにはいくつかの追加機能があります。
リファレンス
このサービスの詳細については、Docs API のリファレンス ドキュメントをご覧ください。Apps Script のすべての高度なサービスと同様に、高度なドキュメント サービスでは、公開 API と同じオブジェクト、メソッド、パラメータを使用します。詳細については、メソッド シグネチャの決定方法をご覧ください。
問題を報告したり、その他のサポートを見つけたりするには、Docs API サポートガイドをご覧ください。
サンプルコード
次のサンプルコードでは、API のバージョン 1 を使用しています。
ドキュメントの作成
このサンプルでは、新しいドキュメントを作成します。
テキストの検索と置換
このサンプルでは、ドキュメント内のすべてのタブでテキストのペアを検索して置換します。これは、テンプレート ドキュメントのコピー内のプレースホルダをデータベースの値に置き換える場合に便利です。
テキストを挿入してスタイルを設定する
このサンプルでは、ドキュメントの最初のタブの先頭に新しいテキストを挿入し、特定のフォントとサイズでスタイルを設定します。可能な場合は、効率を高めるために複数のオペレーションを 1 つの batchUpdate
呼び出しにバッチ処理する必要があります。
最初の段落を読み上げます
このサンプルでは、ドキュメントの最初のタブの最初の段落のテキストをログに記録します。Docs API の段落は構造化されているため、複数のサブ要素のテキストを結合する必要があります。
ベスト プラクティス
バッチ アップデート
高度なドキュメント サービスを使用する場合は、ループで batchUpdate
を呼び出すのではなく、複数のリクエストを配列に結合します。
しない - ループ内で batchUpdate
を呼び出す。
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
Docs.Documents.batchUpdate({
requests: [{
replaceAllText: ...
}]
}, docId);
}
行う - 更新の配列を使用して batchUpdate
を呼び出します。
var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
requests.push({ replaceAllText: ... });
}
Docs.Documents.batchUpdate({
requests: requests
}, docId);
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-08-31 UTC。
[null,null,["最終更新日 2025-08-31 UTC。"],[[["\u003cp\u003eThe advanced Docs service in Apps Script enables programmatic reading, editing, and formatting of Google Docs content using the Google Docs API.\u003c/p\u003e\n"],["\u003cp\u003eWhile often requiring the enabling of advanced services, it offers more features compared to the built-in Docs service.\u003c/p\u003e\n"],["\u003cp\u003eThis service mirrors the functionality of the public Docs API, allowing scripts to leverage its objects, methods, and parameters.\u003c/p\u003e\n"],["\u003cp\u003eSample code snippets are provided for tasks like creating documents, finding and replacing text, inserting and styling text, and reading paragraphs.\u003c/p\u003e\n"],["\u003cp\u003eFor optimal performance, batch multiple requests into a single \u003ccode\u003ebatchUpdate\u003c/code\u003e call instead of using loops.\u003c/p\u003e\n"]]],[],null,["# Advanced Docs Service\n\nThe advanced Docs service allows you to use the\n[Google Docs API](/docs/api) in Apps Script. Much like Apps Script's\n[built-in Docs service](/apps-script/reference/document),\nthis API allows scripts to read, edit, and format content in Google Docs. In\nmost cases the built-in service is easier to use, but this advanced service\nprovides a few extra features.\n| **Note:** This is an advanced service that you must [enable before use](/apps-script/guides/services/advanced). Follow the [quickstart](/docs/api/quickstart/apps-script) for step-by-step instructions on how to get started.\n\nReference\n---------\n\nFor detailed information on this service, see the\n[reference documentation](/docs/api/reference/rest) for the Docs API.\nLike all advanced services in Apps Script, the advanced Docs service uses the\nsame objects, methods, and parameters as the public API. For more information, see [How method signatures are determined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n\nTo report issues and find other support, see the\n[Docs API support guide](/docs/api/support).\n\nSample code\n-----------\n\nThe sample code below uses [version 1](/docs/api/reference/rest) of the API.\n\n### Create document\n\nThis sample creates a new document. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Create a new document.\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create\n * @return {string} documentId\n */\nfunction createDocument() {\n try {\n // Create document with title\n const document = Docs.Documents.create({'title': 'My New Document'});\n console.log('Created document with ID: ' + document.documentId);\n return document.documentId;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', e.message);\n }\n}\n```\n\nFind and replace text\n---------------------\n\nThis sample finds and replaces pairs of text across all tabs in a document. This\ncan be useful when replacing placeholders in a copy of a template document with\nvalues from a database. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Performs \"replace all\".\n * @param {string} documentId The document to perform the replace text operations on.\n * @param {Object} findTextToReplacementMap A map from the \"find text\" to the \"replace text\".\n * @return {Object} replies\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate\n */\nfunction findAndReplace(documentId, findTextToReplacementMap) {\n const requests = [];\n for (const findText in findTextToReplacementMap) {\n const replaceText = findTextToReplacementMap[findText];\n // One option for replacing all text is to specify all tab IDs.\n const request = {\n replaceAllText: {\n containsText: {\n text: findText,\n matchCase: true\n },\n replaceText: replaceText,\n tabsCriteria: {\n tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],\n }\n }\n };\n // Another option is to omit TabsCriteria if you are replacing across all tabs.\n const request = {\n replaceAllText: {\n containsText: {\n text: findText,\n matchCase: true\n },\n replaceText: replaceText\n }\n };\n requests.push(request);\n }\n try {\n const response = Docs.Documents.batchUpdate({'requests': requests}, documentId);\n const replies = response.replies;\n for (const [index] of replies.entries()) {\n const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0;\n console.log('Request %s performed %s replacements.', index, numReplacements);\n }\n return replies;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error : %s', e.message);\n }\n}\n```\n\nInsert and style text\n---------------------\n\nThis sample inserts new text at the start of the first tab in the document and\nstyles it with a specific font and size. Note that when possible you should\nbatch together multiple operations into a single `batchUpdate` call for\nefficiency. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Insert text at the beginning of the first tab in the document and then style\n * the inserted text.\n * @param {string} documentId The document the text is inserted into.\n * @param {string} text The text to insert into the document.\n * @return {Object} replies\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate\n */\nfunction insertAndStyleText(documentId, text) {\n const requests = [{\n insertText: {\n location: {\n index: 1,\n // A tab can be specified using its ID. When omitted, the request is\n // applied to the first tab.\n // tabId: TAB_ID\n },\n text: text\n }\n },\n {\n updateTextStyle: {\n range: {\n startIndex: 1,\n endIndex: text.length + 1\n },\n textStyle: {\n fontSize: {\n magnitude: 12,\n unit: 'PT'\n },\n weightedFontFamily: {\n fontFamily: 'Calibri'\n }\n },\n fields: 'weightedFontFamily, fontSize'\n }\n }];\n try {\n const response =Docs.Documents.batchUpdate({'requests': requests}, documentId);\n return response.replies;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with an error %s', e.message);\n }\n}\n```\n\nRead first paragraph\n--------------------\n\nThis sample logs the text of the first paragraph of the first tab in the\ndocument. Because of the structured nature of paragraphs in the\nDocs API, this involves combining the text of multiple sub-elements. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Read the first paragraph of the first tab in a document.\n * @param {string} documentId The ID of the document to read.\n * @return {Object} paragraphText\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get\n */\nfunction readFirstParagraph(documentId) {\n try {\n // Get the document using document ID\n const document = Docs.Documents.get(documentId, {'includeTabsContent': true});\n const firstTab = document.tabs[0];\n const bodyElements = firstTab.documentTab.body.content;\n for (let i = 0; i \u003c bodyElements.length; i++) {\n const structuralElement = bodyElements[i];\n // Print the first paragraph text present in document\n if (structuralElement.paragraph) {\n const paragraphElements = structuralElement.paragraph.elements;\n let paragraphText = '';\n\n for (let j = 0; j \u003c paragraphElements.length; j++) {\n const paragraphElement = paragraphElements[j];\n if (paragraphElement.textRun !== null) {\n paragraphText += paragraphElement.textRun.content;\n }\n }\n console.log(paragraphText);\n return paragraphText;\n }\n }\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', e.message);\n }\n}\n```\n\nBest Practices\n--------------\n\n### Batch Updates\n\nWhen using the advanced Docs service, combine multiple requests in an array\nrather than calling `batchUpdate` in a loop.\n\nDon't --- Call `batchUpdate` in a loop. \n\n var textToReplace = ['foo', 'bar'];\n for (var i = 0; i \u003c textToReplace.length; i++) {\n Docs.Documents.batchUpdate({\n requests: [{\n replaceAllText: ...\n }]\n }, docId);\n }\n\nDo --- Call `batchUpdate` with an array of\nupdates. \n\n var requests = [];\n var textToReplace = ['foo', 'bar'];\n for (var i = 0; i \u003c textToReplace.length; i++) {\n requests.push({ replaceAllText: ... });\n }\n\n Docs.Documents.batchUpdate({\n requests: requests\n }, docId);"]]