![](/img/trans.png)
[英]How do I extract a specific Column from google sheets using Google Script?
[英]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 文檔中應用一個標簽,該標簽動態地獲取這些帶有變量值的整列的值?
預期結果:
此外,如何在腳本中設置具有固定值的列,例如。 (黃色)和帶有變量值的列,例如。 (穿藍色衣服)?
而且,無論如何,如果我過濾電子表格,腳本將不起作用,為什么?
john
和25/05/1998
都相同。%
括起來。我可以像上面那樣理解。 如果我的理解是正確的,這個答案怎么樣? 請將此視為幾種可能的答案之一。
此示例腳本的流程如下。
在運行腳本之前,請設置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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.