我有一個腳本,它將 Google Doc 模板中的每個 {{Keyword}} 替換為 Google Sheet 中每一行的資料。(下面的示例表)
| 姓名 | 地址 | 城市 | 檔案鏈接 |
|---|---|---|---|
| 名稱 1 | 地址1 | 城市 1 | 腳本在此處寫入新的檔案 URL |
| 名稱 2 | 地址2 | 城市 2 | 腳本在此處寫入新的檔案 URL |
這是我當前正在運行的代碼(成功):
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Documents & Mail Merge')
.addItem('Generate Documents', 'createNewGoogleDocs')
.addSeparator()
.addToUi();
}
function createNewGoogleDocs() {
const documentLink_Col = ("Document Link");
const template = DriveApp.getFileById('templateIdGoesHere');
const destinationFolder = DriveApp.getFolderById('destinationFolderIdGoesHere');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
const data = sheet.getDataRange().getDisplayValues();
const heads = data[0]; // Assumes row 1 contains the column headings
const documentLink_ColIndex = heads.indexOf(documentLink_Col);
data.forEach(function(row, index){
if(index === 0 || row[documentLink_ColIndex]) return;
const templateCopy = template.makeCopy(`${row[0]} ${row[1]} Report`, destinationFolder); //create a copy of the template document
const templateCopyId = DocumentApp.openById(templateCopy.getId());
const templateCopyBody = templateCopyId.getBody();
templateCopyBody.replaceText('{{Name}}', row[0]);
templateCopyBody.replaceText('{{Address}}', row[1]);
templateCopyBody.replaceText('{{City}}', row[2]);
templateCopyId.saveAndClose();
const url = templateCopyId.getUrl();
sheet.getRange(index 1 , documentLink_ColIndex 1).setValue(url);
})
}
我想要實作/更改功能:替換硬編碼的 {{Placeholders}},就像templateCopyBody.replaceText('{{Name}}', row[0]);在模板檔案中將任何列名視為潛在 {{Placeholder}} 的另一種方法一樣。所以基本上我應該可以自由地編輯、添加、移動或洗掉作業表中的列,而不必再對它們進行硬編碼,而只需調整模板。
也許有幫助,我發現了一種類似的腳本,它使用 Gmail 草稿而不是 Google Doc 作為模板,以下是我理解的兩個功能,可以滿足我的需要:
/**
* Fill template string with data object
* @see https://stackoverflow.com/a/378000/1027723
* @param {string} template string containing {{}} markers which are replaced with data
* @param {object} data object used to replace {{}} markers
* @return {object} message replaced with data
*/
function fillInTemplateFromObject_(template, data) {
// We have two templates one for plain text and the html body
// Stringifing the object means we can do a global replace
let template_string = JSON.stringify(template);
// Token replacement
template_string = template_string.replace(/{{[^{}] }}/g, key => {
return escapeData_(data[key.replace(/[{}] /g, "")] || "");
});
return JSON.parse(template_string);
}
/**
* Escape cell data to make JSON safe
* @see https://stackoverflow.com/a/9204218/1027723
* @param {string} str to escape JSON special characters from
* @return {string} escaped string
*/
function escapeData_(str) {
return str
.replace(/[\\]/g, '\\\\')
.replace(/[\"]/g, '\\\"')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t');
};
}
雖然我是一個完整的菜鳥,但我無法在原始函式fillInTemplateFromObject_內的回圈內成功呼叫該函式,這是我想我應該做的嗎?foreachcreateNewGoogleDocs
由于缺乏經驗,任何可能的措辭不佳,請提前道歉,并提前感謝大家的支持。
uj5u.com熱心網友回復:
在您的情況下,如何進行以下修改?
修改后的腳本:
請設定模板檔案 ID 和檔案夾 ID。
function createNewGoogleDocs() {
const documentLink_Col = "Document Link";
const template = DriveApp.getFileById('templateIdGoesHere');
const destinationFolder = DriveApp.getFolderById('destinationFolderIdGoesHere');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
const [header, ...values] = sheet.getDataRange().getDisplayValues();
const documentLink_ColIndex = header.indexOf(documentLink_Col);
const data = values.map(r => {
const temp = r.reduce((o, c, j) => {
o[header[j]] = c;
return o;
}, {});
return { filename: `${r[0]} ${r[1]} Report`, obj: temp };
});
const v = data.map(({ filename, obj }) => {
if (obj[documentLink_Col]) return [obj[documentLink_Col]];
const templateCopy = template.makeCopy(filename, destinationFolder); //create a copy of the template document
const templateCopyId = DocumentApp.openById(templateCopy.getId());
const templateCopyBody = templateCopyId.getBody();
Object.entries(obj).forEach(([k, v]) => templateCopyBody.replaceText(`{{${k}}}`, v));
templateCopyId.saveAndClose();
const url = templateCopyId.getUrl();
return [url];
});
sheet.getRange(2, documentLink_ColIndex 1, v.length, 1).setValues(v);
}
在此修改中,創建了一個包括標頭和值的物件。使用這個物件,占位符被動態使用。并且,在創建檔案后,將 URL 放入
Document Link.例如,當您更改電子表格的標題值和模板檔案的占位符時,可以使用此腳本。
參考:
- 地圖()
- 減少()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464641.html
標籤:javascript 谷歌应用脚本 谷歌表格 谷歌文档
上一篇:如何通過url傳遞變數?
