Gelişmiş Dokümanlar Hizmeti
Koleksiyonlar ile düzeninizi koruyun
İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.
Gelişmiş Dokümanlar hizmeti, Apps Komut Dosyası'nda Google Dokümanlar API'yi kullanmanıza olanak tanır. Apps Komut Dosyası'nın yerleşik Dokümanlar hizmetine benzer şekilde bu API, komut dosyalarının Google Dokümanlar'daki içeriği okumasına, düzenlemesine ve biçimlendirmesine olanak tanır. Çoğu durumda yerleşik hizmetin kullanımı daha kolaydır ancak bu gelişmiş hizmet birkaç ek özellik sunar.
Referans
Bu hizmetle ilgili ayrıntılı bilgi için Dokümanlar API'sinin referans belgelerine bakın.
Apps Komut Dosyası'ndaki tüm gelişmiş hizmetler gibi, gelişmiş Dokümanlar hizmeti de herkese açık API ile aynı nesneleri, yöntemleri ve parametreleri kullanır. Daha fazla bilgi için Yöntem imzaları nasıl belirlenir? başlıklı makaleyi inceleyin.
Sorunları bildirmek ve diğer destek seçeneklerini öğrenmek için Docs API destek kılavuzuna bakın.
Örnek kod
Aşağıdaki örnek kodda API'nin 1. sürümü kullanılmaktadır.
Belge oluştur
Bu örnek, yeni bir doküman oluşturur.
Metin bulma ve değiştirme
Bu örnek, bir dokümandaki tüm sekmelerde metin çiftlerini bulup değiştirir. Bu, bir şablon belgesinin kopyasındaki yer tutucuları bir veritabanındaki değerlerle değiştirirken faydalı olabilir.
Metin ekleme ve stilini belirleme
Bu örnek, dokümandaki ilk sekmenin başına yeni metin ekler ve belirli bir yazı tipi ve boyutta biçimlendirir. Mümkün olduğunda verimlilik için birden fazla işlemi tek bir batchUpdate
çağrısında toplu olarak göndermeniz gerektiğini unutmayın.
İlk paragrafı oku
Bu örnek, dokümandaki ilk sekmenin ilk paragrafının metnini kaydeder. Docs API'deki paragrafların yapılandırılmış yapısı nedeniyle bu işlem, birden fazla alt öğenin metnini birleştirmeyi içerir.
En İyi Uygulamalar
Toplu Güncellemeler
Gelişmiş Dokümanlar hizmetini kullanırken batchUpdate
işlevini döngü içinde çağırmak yerine birden fazla isteği bir dizide birleştirin.
Yapmayın: batchUpdate
işlevini döngü içinde çağırmayın.
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
Docs.Documents.batchUpdate({
requests: [{
replaceAllText: ...
}]
}, docId);
}
Yapılacaklar: Bir dizi güncellemeyle batchUpdate
işlevini çağırın.
var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
requests.push({ replaceAllText: ... });
}
Docs.Documents.batchUpdate({
requests: requests
}, docId);
Aksi belirtilmediği sürece bu sayfanın içeriği Creative Commons Atıf 4.0 Lisansı altında ve kod örnekleri Apache 2.0 Lisansı altında lisanslanmıştır. Ayrıntılı bilgi için Google Developers Site Politikaları'na göz atın. Java, Oracle ve/veya satış ortaklarının tescilli ticari markasıdır.
Son güncelleme tarihi: 2025-08-31 UTC.
[null,null,["Son güncelleme tarihi: 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);"]]