Google Docs API 的其中一種實用應用程式,是將一或多個資料來源的資訊合併成一個文件。
本頁面概述如何從外部來源擷取資料,並將其插入現有的範本文件中。
「範本」是一種特殊類型的文件,內含所有利用範本建立的文件的固定文字及可放置其他動態文字的指定預留位置。例如,合約範本可能包含固定內容,以及接收器名稱、地址和其他詳細資料的位置。然後,應用程式可以將客戶專屬資料合併至範本,以建立完成的文件。
這個方法非常實用,原因如下:
設計人員可以輕鬆使用 Google 文件編輯器微調文件的設計。比起調整應用程式中的參數,以設定算繪的版面配置,這個做法會簡單得多。
將內容與簡報區隔開來是知名的設計原則,而且具有許多優點。
基本食譜
以下範例說明如何使用 Docs API 將資料合併成文件:
請使用預留位置內容建立文件,以便設定和格式。所有要取代的文字格式都會保留下來。
針對您要插入的每個元素,將預留位置內容換成標記。請務必使用平常不會出現的字串。例如,
{{account-holder-name}}
可能是好標記。在程式碼中使用 Google Drive API 建立文件副本。
在程式碼中,使用 Docs API 的
batchUpdate()
方法搭配文件名稱,並加入ReplaceAllTextRequest
。
文件 ID 會參照文件,且可以從網址取得
https://docs.google.com/document/d/documentId/edit
範例
請參考下列範例,使用實際值取代範本中的 2 個欄位以產生成完成的文件。
如要執行這項合併作業,您可以使用以下程式碼。
Java
String customerName = "Alice"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); String date = formatter.format(LocalDate.now()); List<Request> requests = new ArrayList<>(); requests.add(new Request() .setReplaceAllText(new ReplaceAllTextRequest() .setContainsText(new SubstringMatchCriteria() .setText("{{customer-name}}") .setMatchCase(true)) .setReplaceText(customerName))); requests.add(new Request() .setReplaceAllText(new ReplaceAllTextRequest() .setContainsText(new SubstringMatchCriteria() .setText("{{date}}") .setMatchCase(true)) .setReplaceText(date))); BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest(); service.documents().batchUpdate(documentId, body.setRequests(requests)).execute();
Node.js
let customerName = 'Alice'; let date = yyyymmdd() let requests = [ { replaceAllText: { containsText: { text: '{{customer-name}}', matchCase: true, }, replaceText: customerName, }, }, { replaceAllText: { containsText: { text: '{{date}}', matchCase: true, }, replaceText: date, }, }, ]; google.options({auth: auth}); google .discoverAPI( 'https://docs.googleapis.com/$discovery/rest?version=v1&key={YOUR_API_KEY}') .then(function(docs) { docs.documents.batchUpdate( { documentId: '1yBx6HSnu_gbV2sk1nChJOFo_g3AizBhr-PpkyKAwcTg', resource: { requests, }, }, (err, {data}) => { if (err) return console.log('The API returned an error: ' + err); console.log(data); }); });
Python
customer_name = 'Alice' date = datetime.datetime.now().strftime("%y/%m/%d") requests = [ { 'replaceAllText': { 'containsText': { 'text': '{{customer-name}}', 'matchCase': 'true' }, 'replaceText': customer_name, }}, { 'replaceAllText': { 'containsText': { 'text': '{{date}}', 'matchCase': 'true' }, 'replaceText': str(date), } } ] result = service.documents().batchUpdate( documentId=document_id, body={'requests': requests}).execute()
管理範本
如果是應用程式定義和擁有的範本文件,請使用代表應用程式的專屬帳戶建立範本。建議您選擇服務帳戶,避免因 Google Workspace 政策限制共用功能的複雜問題。
使用範本建立文件執行個體時,一律使用使用者憑證。這樣一來,使用者就能完全掌控文件產生的內容,避免出現雲端硬碟中與個別使用者限制相關的資源調度問題。
如要使用服務帳戶建立範本,請使用應用程式憑證執行下列步驟:
- 在 Docs API 中使用 documents.create 建立文件。
- 更新權限,允許文件收件者在 Drive API 中使用 permissions.create 讀取文件。
- 更新權限,允許範本作者使用 Drive API 中的 permissions.create 寫入範本。
- 視需要編輯範本。
如要建立文件執行個體,請使用使用者憑證執行下列步驟:
- 在 Drive API 中使用 files.copy 建立範本的副本。
- 使用 Docs API 中的 documents.BatchUpdate 取代值。