Google Sheets生成的二维码无法保存,脚本运行异常求助
解决Google Sheets中批量下载IMAGE公式生成二维码的问题
错误原因分析
TypeError: url.startsWith is not a function 这个报错的核心问题是:你代码里的url变量不是字符串类型——大概率是直接从单元格取内容时,拿到的是IMAGE公式渲染后的图片对象,而非公式里的二维码原始URL。
可行的批量下载脚本
下面是可以直接用的脚本,能自动提取单元格公式里的二维码URL,批量下载并保存到你的Google Drive:
function downloadQRCodes() { // 这里改成你的工作表名称、二维码所在单元格范围(比如"A2:A10") const sheetName = "Sheet1"; const rangeStr = "A2:A10"; const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); const range = sheet.getRange(rangeStr); const formulas = range.getFormulas(); // 取单元格公式,不是渲染后的图片 // 自动创建存二维码的文件夹,不存在就新建 const folderName = "QR Codes"; let folder = DriveApp.getFoldersByName(folderName).next() || DriveApp.createFolder(folderName); formulas.forEach((row, rowIndex) => { const formula = row[0]; if (formula && formula.startsWith('=IMAGE(')) { // 从公式里抠出二维码的URL const urlMatch = formula.match(/"(https:\/\/api.qrserver.com.*?)"/); if (urlMatch) { const qrUrl = urlMatch[1]; try { const response = UrlFetchApp.fetch(qrUrl); const blob = response.getBlob(); // 用对应行B列的内容当文件名,空的话用默认命名 const fileName = sheet.getRange(range.getRow() + rowIndex, 2).getValue() || `QR_Code_${rowIndex + 1}`; folder.createFile(blob.setName(`${fileName}.png`)); Logger.log(`已保存:${fileName}.png`); } catch (e) { Logger.log(`行${rowIndex + range.getRow()}下载失败:${e}`); } } } }); SpreadsheetApp.getUi().alert("批量下载完成,去Google Drive的「QR Codes」文件夹查看"); }
使用步骤
- 打开你的Google Sheets,点顶部菜单栏「扩展程序」→「Apps 脚本」
- 删除默认代码,粘贴上面的脚本
- 修改脚本开头的
sheetName和rangeStr,匹配你的工作表和二维码所在位置 - 点脚本编辑器顶部的「运行」,第一次运行需要授权,跟着提示完成就行
- 运行完会弹提示,去Google Drive找「QR Codes」文件夹就能看到下载好的二维码
内容的提问来源于stack exchange,提问作者Kelley
相关产品推荐
相关产品推荐

