【发布时间】:2021-02-16 20:39:36
【问题描述】:
我目前有一个脚本,可以将 Google Sheet 中的数据合并到 Google Doc 模板中。对于工作表的每一行,使用该行中的标题数据创建一个新文档。该脚本工作正常,但不是我的工作。它已传给我,但我对 Google Script 的熟练程度不足以弄清楚我想要实现的目标。
理想情况下,我想知道是否可以在脚本运行时检查文档文件是否已经存在。它会这样做,因为创建的每个文档都使用工作表中的标题数据。如果文档确实存在,那么可以在该工作表中更新数据,而不是创建它的新版本。
脚本如下
function mergeDocSheet() {
const TEMPLATE_ID = '16YfyeDjGDp-88McAtLCQQyZ1xz4QX5z';// Google Doc template ID
const SS_ID = '1C5gtJCSzHMuSz-oVWEItl2EUVRDwF5iH_'; // Google Sheet ID
const SHEET_NAME = "data"; // Google Sheet Tab name
const MAPPED = mappedDocToSheet;
const FILE_NAME = ["Titre de la formation"] // Header IDs from sheet.
docMerge(TEMPLATE_ID,SS_ID,SHEET_NAME,MAPPED, FILE_NAME);
}
function docMerge(templateID,ssID, sheetName, mapped, fileNameData, rowLen = "auto"){
//Get the Spreadsheet and sheet tab
const ss = SpreadsheetApp.openById(ssID);
const sheet = ss.getSheetByName(sheetName);
//Get number of rows to process
rowLen = (rowLen = "auto") ? getRowLen() - 1 : rowLen;
//Gets the range of data in the sheet then grabs the values of the range
const range = sheet.getRange(1,1,rowLen,sheet.getDataRange().getNumColumns());
const matrix = range.getValues();
// Searches the file mapped object and finds the corresponding number returns the column number in an array.
const fileNameRows = getFileNameRows()
//Loops through each row of the sheet grabbing the data from each row and putting it into a new doc.
for(let i = 1; i < rowLen; i++){
let row = matrix[i];
//Get the title for the file.
let fileName = buildFileName(row)
let newDoc = DriveApp.getFileById(templateID).makeCopy(fileName);
updateFileData(row, newDoc.getId());
};
function updateFileData(rowArray, doc){
//Loops through the mapped object.
mapped.forEach(function(element){
let textID = `\{\{${element.doc}\}\}`
DocumentApp.openById(doc).getBody().replaceText(textID,
rowArray[element.col]);
});
};
function buildFileName(rowArry){
let fileNameArray = fileNameRows.map(ele => rowArry[ele]);
return fileNameArray.join("_");
};
function getFileNameRows(){
//Map the column indexes from fileNameData
let fileNameLocs = fileNameData
.flatMap(name => {
return mapped.filter(element => element.sheet === name)
.map(ele => ele.col);
});
return fileNameLocs;
};
function getRowLen(){
return sheet.getDataRange().getNumRows();
};
};
是否可以围绕这些行设置某种条件?
let newDoc = DriveApp.getFileById(templateID).makeCopy(fileName);
updateFileData(row, newDoc.getId());
我希望有人能以此为我指明正确的方向。非常感谢任何建议。
【问题讨论】:
-
在谷歌驱动器中可能有相同的文件名
-
我明白了,那么在这种情况下,是否无法检查可能已经创建的同名文件?
标签: google-apps-script google-sheets google-docs mailmerge