簡體   English   中英

如何使用谷歌腳本從谷歌表中提取特定列到谷歌文檔?

[英]How do I extract specific columns from google sheets to google doc using Google Script?

我有一個帶有動態字段標記的 Google Doc,例如%Name% - %Date of Birth% ,它從 A 列和 B 列中的 Google 表格中獲取值:

工作表的屏幕截圖

正如您所看到的,前兩列中的值是相同的,因此我在 google 文檔中的“%”標簽沒有問題,因為它采用相同的值。
問題在於其他列(C、D、E...),其中谷歌工作表上的值是變量。

如何在 Google 文檔中應用一個標簽,該標簽動態地獲取這些帶有變量值的整列的值?

文檔截圖


預期結果:

在此處輸入圖片說明

此外,如何在腳本中設置具有固定值的列,例如。 (黃色)和帶有變量值的列,例如。 (穿藍色衣服)?

而且,無論如何,如果我過濾電子表格,腳本將不起作用,為什么?

在此處輸入圖片說明

  • 您想從電子表格中檢索值並將其放入模板文檔。
  • 在您的電子表格中,“A”和“B”列的所有值對於所有行(如john25/05/1998都相同。
  • 您想通過用電子表格中的值替換占位符來創建一個 Google 文檔。
    • 占位符用%括起來。
  • 您想使用 Google Apps 腳本來實現這一點。

我可以像上面那樣理解。 如果我的理解是正確的,這個答案怎么樣? 請將此視為幾種可能的答案之一。

流動:

此示例腳本的流程如下。

  1. 從電子表格中檢索值。
  2. 創建一個用於放入 Google 文檔的對象。
  3. 復制模板 Google 文檔。
  4. 使用對象將標題值放入復制的文檔中。
    • 在這種情況下,占位符將替換為檢索到的值。
  5. 使用對象放置表值。
    • 在這種情況下,檢索到的值直接放入模板文檔中的表中。

示例腳本:

在運行腳本之前,請設置templateGoogleDocumentID

function myFunction() {
  var templateGoogleDocumentID = "###";  // Please set the template Google Document ID.

  // 1. Retrieve values from Spreadsheet.
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var values = activeSheet.getDataRange().getValues();

  // 2. Create an object for putting to Google Document.
  var object = {headers: {}, table: {}};
  var headerRow = values.shift();
  object.headers[headerRow[0]] = values[0][0];
  object.headers[headerRow[1]] = Utilities.formatDate(values[0][1], Session.getScriptTimeZone(), "yyyy/MM/dd");
  object.table = values.map(r => r.splice(2, 5));

  // 3. Copy a template Google Document.
  var copiedTemplateDoc = DriveApp.getFileById(templateGoogleDocumentID).makeCopy();
  var docId = copiedTemplateDoc.getId();

  // 4. Put the header values to the copied Document using the object.
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();
  Object.keys(object.headers).forEach(h => body.replaceText(`%${h.toLowerCase()}%`, object.headers[h]));

  // 5. Put the table values using the object.
  // If the table rows of Google Document are less than that of Spreadsheet, the rows are added.
  var table = body.getTables()[0];
  var r = object.table.length - table.getNumRows();
  if (r > 0) {
    for (var i = 0; i < r; i++) {
      var tr = table.appendTableRow();
      for (var j = 0; j < 3; j++) {
        tr.appendTableCell();
      }
    }
  }
  object.table.forEach((row, i) => (row.forEach((col, j) => (table.getCell(i, j).setText(col)))));
  doc.saveAndClose();

  // If you want to export the Google Document as PDF file, please use the following script.
  // var newFile = DriveApp.createFile(doc.getBlob());
}

筆記:

  • 在這個修改后的腳本中,請在腳本編輯器中啟用 V8。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM