忽略空单元格



不知是否有人能帮助我。

我已经设置了下面的脚本编码,以生成基于谷歌表格中的数据的谷歌文档模板。我遇到的问题是,当我在谷歌表格中运行AutoFill Docs过程时,它正在创建字母并为任何空单元格添加字母中的空格。

例如,根据客户的详细信息,我有4个标题(地址1、地址2、地址3和地址4),但不是所有这些都填满了。

当字母/google doc生成时,它会为空单元格添加空格(见下文)

鲍勃·史密斯鲍勃路32号

Bobbington

B23 4本对于空单元格,我需要它忽略它们并生成如下字母:

鲍勃·史密斯鲍勃路32号BobbingtonB23 4本

任何帮助都将非常感激。

感谢克里斯

function onOpen() {
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('AutoFill Docs');
menu.addItem('Create New Docs', 'createNewGoogleDocs')
menu.addToUi();

}
function createNewGoogleDocs() {
const googleDocTemplate = DriveApp.getFileById('1oa-BtAhFKsvJ37Dl26Xvt2QTe9HjSz8vE9YVhtXjPA8');
const destinationFolder = DriveApp.getFolderById('1kPVjBvCrdtb6k3bafl-g-s64b40-oH6I')
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Daysavers')
const rows = sheet.getDataRange().getValues();

rows.forEach(function(row, index){
if (index === 0) return;
if (row[10]) return;
const copy = googleDocTemplate.makeCopy(`${row[1]}, ${row[2]} Customer Details` , destinationFolder)
const doc = DocumentApp.openById(copy.getId())
const body = doc.getBody();
body.replaceText('{{Case Reference}}', row[0]);
body.replaceText('{{First Name}}', row[1]);
body.replaceText('{{Last Name}}', row[2]);
body.replaceText('{{Address 1}}', row[3]);
body.replaceText('{{Address 2}}', row[4]);
body.replaceText('{{Address 3}}', row[5]);
body.replaceText('{{Address 4}}', row[6]);
body.replaceText('{{Postcode}}', row[7]);
body.replaceText('{{First Name 2}}', row[8]);
body.replaceText('{{Number}}', row[9]);
doc.saveAndClose();
const url = doc.getUrl();
sheet.getRange(index + 1, 11).setValue(url)
})
}

我猜这不是脚本放空间,但只是地址项之间的空间留下那里。

body.replaceText(' {{Address 2}}', row[4] ? ' ' + row[4] : '');

对3和4也这样做

如果电子表格的行总是保存您想要插入的数据,以正确的顺序,您可以避免在模板中使用多个占位符,只放置一个占位符,然后将所有body.replaceText(...)行替换为一行:

body.replaceText('{{Single Placeholder}}', row.filter(Boolean).join(' '));

row.filter(Boolean)生成一个仅包含非空字符串或非零数值的单元格值的数组,.join(' ')将它们全部连接成一个空格分隔的字符串。

如果您仍然得到换行符,则可能在电子表格单元格中有换行符。用.replace(/n/g,'')

消除它们
body.replaceText('{{Single Placeholder}}', row.filter(Boolean).join(' ').replace(/n/g,'');

最新更新