为何生成PDF文件名显示为0而非表格单元格指定名称?
问题原因与修复方案
错误根源:代码里的文件名拼接语法不符合JavaScript规则,导致计算结果异常:
- JavaScript中字符串拼接需用
+,而非& - 变量无需用
{}包裹,直接调用变量名即可 &会被识别为按位与运算符,非数字字符串会被强制转为0,最终运算结果就是0,所以文件名显示为0
- JavaScript中字符串拼接需用
修复后的代码:
const fileTitle = ss.getRange(i, 2).getValue(); // test1; test2 var blob = Utilities.newBlob(htmlBody, 'text/html') .getAs('application/pdf') .setName(fileTitle + '.pdf'); // 正确的字符串拼接方式 DriveApp.createFile(blob);
- 额外优化建议:可增加空值判断,避免生成无效文件名:
const fileTitle = ss.getRange(i, 2).getValue().trim(); // 处理空文件名的情况,生成带索引的默认名称 const finalFileName = fileTitle ? `${fileTitle}.pdf` : `default_${i}.pdf`; var blob = Utilities.newBlob(htmlBody, 'text/html') .getAs('application/pdf') .setName(finalFileName); DriveApp.createFile(blob);
内容的提问来源于stack exchange,提问作者Agnieszka Liszka
相关产品推荐
相关产品推荐

