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 取代值。