將文字合併至文件

Google Docs API 提供一個實用的應用程式,那就是合併 可以將多個資料來源新增至文件中

本頁面概述如何從外部來源擷取資料並插入 轉換為現有範本文件

「範本」是一種特殊類型的文件,內含相同的固定文字,適用於從範本建立的所有文件,以及指定的預留位置 並放置其他動態文字舉例來說,合約範本可能包含固定內容、接收者名稱、地址和位置 。接著,您的應用程式可以將顧客專屬資料合併至範本 建立完成的文件

這種方法很實用有以下幾個原因:

  • 設計人員可以使用 Google 文件編輯器比起在實際工作環境中 設定轉譯版面配置。

  • 從簡報中區隔內容是一項著名的設計 開發原則有許多好處

合併作業的概念圖。

基本食譜

以下範例說明如何使用 Docs API 將資料合併成文件中:

  1. 使用 建立文件 預留位置內容協助您完成設計和格式。您要取代的任何文字格式都會保留。

  2. 針對每個要插入的元素,將預留位置內容替換為 標記之前。請務必使用不太可能發生的字串。例如: 「{{account-holder-name}}」可能是個不錯的標記。

  3. 在程式碼中,使用 Google Drive API 建立文件副本。

  4. 在程式碼中,將 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<>();
// One option for replacing all text is to specify all tab IDs.
requests.add(new Request()
        .setReplaceAllText(new ReplaceAllTextRequest()
                .setContainsText(new SubstringMatchCriteria()
                        .setText("{{customer-name}}")
                        .setMatchCase(true))
                .setReplaceText(customerName)
                .setTabsCriteria(new TabsCriteria()
                        .addTabIds(TAB_ID_1)
                        .addTabIds(TAB_ID_2)
                        .addTabIds(TAB_ID_3))));
// Another option is to omit TabsCriteria if you are replacing across all tabs.
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 = [
    // One option for replacing all text is to specify all tab IDs.
    {
      replaceAllText: {
        containsText: {
          text: '{{customer-name}}',
          matchCase: true,
        },
        replaceText: customerName,
        tabsCriteria: {
          tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],
        },
      },
    },
    // Another option is to omit TabsCriteria if you are replacing across all tabs.
    {
      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 = [
        # One option for replacing all text is to specify all tab IDs.
        {
        'replaceAllText': {
            'containsText': {
                'text': '{{customer-name}}',
                'matchCase':  'true'
            },
            'replaceText': customer_name,
            'tabsCriteria': {
                'tabIds': [TAB_ID_1, TAB_ID_2, TAB_ID_3],
            },
        }},
        # Another option is to omit TabsCriteria if you are replacing across all tabs.
        {
        'replaceAllText': {
            'containsText': {
                'text': '{{date}}',
                'matchCase':  'true'
            },
            'replaceText': str(date),
        }
    }
]

result = service.documents().batchUpdate(
    documentId=document_id, body={'requests': requests}).execute()

管理範本

如果是應用程式定義和擁有的範本文件,請建立 使用代表應用程式的專屬帳戶建立範本 服務帳戶 這種做法相當適合您,且可避免違反 Google Workspace 政策。 限制共用。

透過範本建立文件執行個體時,請一律使用 建立使用者憑證這樣一來,使用者就能完全掌控 產生的文件,避免發生與每位使用者相關的資源調度問題 。

如要使用服務帳戶建立範本,請執行下列步驟: 應用程式憑證:

  1. 使用 建立文件 documents.create
  2. 更新權限,允許文件收件者使用 permissions.create (在 Drive API
  3. 更新權限,允許範本作者使用 寫入 permissions.create (在 Drive API
  4. 視需要編輯範本。

如要建立文件執行個體,請執行下列步驟: 包含使用者憑證:

  1. 使用 files.copy
  2. 以下列方式替換值: documents.batchUpdate