Zaawansowana usługa Dokumentów
Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
Zaawansowana usługa Dokumentów umożliwia korzystanie z interfejsu Google Docs API w Apps Script. Podobnie jak wbudowana usługa Dokumentów w Apps Script ten interfejs API umożliwia skryptom odczytywanie, edytowanie i formatowanie treści w Dokumentach Google. W większości przypadków usługa wbudowana jest łatwiejsza w użyciu, ale ta usługa zaawansowana zapewnia kilka dodatkowych funkcji.
Dokumentacja
Szczegółowe informacje o tej usłudze znajdziesz w dokumentacji referencyjnej interfejsu Docs API.
Podobnie jak wszystkie usługi zaawansowane w Apps Script, zaawansowana usługa Dokumentów korzysta z tych samych obiektów, metod i parametrów co publiczny interfejs API. Więcej informacji znajdziesz w artykule Jak określane są sygnatury metod.
Aby zgłosić problemy i uzyskać inną pomoc, zapoznaj się z przewodnikiem pomocy dotyczącym interfejsu Docs API.
Przykładowy kod
Poniższy przykładowy kod korzysta z wersji 1 interfejsu API.
Utwórz dokument
Ten przykład tworzy nowy dokument.
Znajdowanie i zastępowanie tekstu
Ten przykład znajduje i zastępuje pary tekstu na wszystkich kartach w dokumencie. Może to być przydatne podczas zastępowania zmiennych w kopii dokumentu szablonu wartościami z bazy danych.
Wstawianie i formatowanie tekstu
Ten przykład wstawia nowy tekst na początku pierwszej karty w dokumencie i
formatuje go za pomocą określonej czcionki i rozmiaru. Pamiętaj, że w miarę możliwości należy łączyć wiele operacji w jedno wywołanie batchUpdate
, aby zwiększyć wydajność.
Przeczytaj pierwszy akapit
Ten przykład rejestruje tekst pierwszego akapitu pierwszej karty w dokumencie. Ze względu na uporządkowaną strukturę akapitów w interfejsie Docs API wymaga to połączenia tekstu z wielu elementów podrzędnych.
Sprawdzone metody
Aktualizacje zbiorcze
Jeśli korzystasz z zaawansowanej usługi Dokumenty, łącz wiele żądań w tablicę zamiast wywoływać batchUpdate
w pętli.
Nie – wywołuje funkcję batchUpdate
w pętli.
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
Docs.Documents.batchUpdate({
requests: [{
replaceAllText: ...
}]
}, docId);
}
Do – wywołaj batchUpdate
z tablicą aktualizacji.
var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
requests.push({ replaceAllText: ... });
}
Docs.Documents.batchUpdate({
requests: requests
}, docId);
O ile nie stwierdzono inaczej, treść tej strony jest objęta licencją Creative Commons – uznanie autorstwa 4.0, a fragmenty kodu są dostępne na licencji Apache 2.0. Szczegółowe informacje na ten temat zawierają zasady dotyczące witryny Google Developers. Java jest zastrzeżonym znakiem towarowym firmy Oracle i jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2025-08-31 UTC.
[null,null,["Ostatnia aktualizacja: 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);"]]