1 回答
TA貢獻1784條經驗 獲得超8個贊
您想從電子表格中檢索值并放入模板文檔。
在您的電子表格中,“A”和“B”列的所有值對于所有行(如
john和)都是相同的25/05/1998。您希望通過將占位符替換為電子表格中的值來創建一個 Google 文檔。
占位符由 括起來
%。您想使用 Google Apps 腳本實現此目的。
我可以像上面那樣理解。如果我的理解是正確的,這個答案怎么樣?請認為這只是幾個可能的答案之一。
流動:
該示例腳本的流程如下。
從電子表格中檢索值。
創建一個用于放入 Google 文檔的對象。
復制模板 Google 文檔。
使用對象將標題值放入復制的 Document 中。
在這種情況下,占位符將替換為檢索到的值。
使用對象放置表值。
在這種情況下,將檢索到的值直接放入模板 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。
添加回答
舉報
