亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕桂英3389331 2022-06-05 16:22:04
我有一個帶有動態字段標記的 Google Doc,例如%Name% - %Date of Birth%,它從 A 列和 B 列中的谷歌表中獲取值:工作表截圖正如您所看到的,前 2 列中的值是相同的,因此我在 google 文檔中的“%”標簽沒有問題,因為它采用相同的值。問題在于其他列(C,D,E ...),其中谷歌表上的值是變量。如何在 Google 文檔中應用一個標簽,該標簽動態地獲取這些帶有變量值的整個列的值?預期結果:此外,如何在腳本中設置具有固定值的列,例如。(黃色)和具有變量值的列,例如。(穿藍色衣服)?而且,無論如何,如果我過濾電子表格,腳本就不起作用,為什么?
查看完整描述

1 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

  • 您想從電子表格中檢索值并放入模板文檔。

  • 在您的電子表格中,“A”和“B”列的所有值對于所有行(如john和)都是相同的25/05/1998。

  • 您希望通過將占位符替換為電子表格中的值來創建一個 Google 文檔。

    • 占位符由 括起來%

  • 您想使用 Google Apps 腳本實現此目的。

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

流動:

該示例腳本的流程如下。

  1. 從電子表格中檢索值。

  2. 創建一個用于放入 Google 文檔的對象。

  3. 復制模板 Google 文檔。

  4. 使用對象將標題值放入復制的 Document 中。

    • 在這種情況下,占位符將替換為檢索到的值。

  5. 使用對象放置表值。

    • 在這種情況下,將檢索到的值直接放入模板 Document 中的表中。

示例腳本:

在運行腳本之前,請先設置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。


查看完整回答
反對 回復 2022-06-05
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號