修改GAS脚本实现指定Google Sheet工作表导出CSV并保留时间戳
修改Google Apps Script实现指定工作表导出CSV并保留时间戳
要实现指定工作表导出且保留时间戳,只需要在原有脚本基础上添加工作表指定逻辑,同时在前端页面增加选择/输入工作表的交互,具体修改如下:
一、修改后端GAS脚本
原脚本只处理第一个工作表,现在我们添加参数接收指定的工作表名称(或索引),并验证存在性后处理:
function doGet() { return HtmlService.createHtmlOutputFromFile('Index'); } function exportSheetToCsv(sheetName) { // 获取当前Spreadsheet const ss = SpreadsheetApp.getActiveSpreadsheet(); // 根据传入的工作表名称获取工作表,若不存在则返回错误 const sheet = ss.getSheetByName(sheetName); if (!sheet) { throw new Error(`找不到名为"${sheetName}"的工作表`); } // 获取所有数据行 const rows = sheet.getDataRange().getValues(); // 处理每行数据,重点保留时间戳格式 const csvRows = rows.map(row => { return row.map(cell => { // 判断是否为时间戳对象(Date类型) if (cell instanceof Date) { // 按照自定义格式保留,可根据需求修改格式字符串 return Utilities.formatDate(cell, Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss"); } // 处理包含逗号、引号的文本,添加引号包裹避免CSV格式错误 else if (typeof cell === 'string' && (cell.includes(',') || cell.includes('"'))) { return `"${cell.replace(/"/g, '""')}"`; } return cell; }).join(','); }); // 拼接CSV内容 const csvContent = csvRows.join('\n'); // 转换为Blob对象,设置MIME类型 const blob = Utilities.newBlob(csvContent, 'text/csv', `${sheetName}.csv`); // 返回下载链接所需的Blob数据和文件名 return { data: Utilities.base64Encode(blob.getBytes()), filename: `${sheetName}.csv` }; }
关键修改点:
- 新增
sheetName参数,用于接收前端传入的工作表名称 - 添加工作表存在性校验,避免因输入错误导致的无意义报错
- 生成CSV时使用指定工作表的数据,而非默认的第一个工作表
二、修改前端HTML页面(Index.html)
添加输入框让用户填写要导出的工作表名称,同时修改提交逻辑传递该参数:
<!DOCTYPE html> <html> <head> <base target="_top"> <style> .container { margin: 20px; } input, button { padding: 8px; margin: 5px 0; } </style> </head> <body> <div class="container"> <h3>导出指定工作表为CSV(保留时间戳)</h3> <div> <label>工作表名称:</label> <input type="text" id="sheetName" placeholder="输入要导出的工作表名称"> </div> <button onclick="exportCsv()">导出CSV</button> <div id="error" style="color: red; margin-top: 10px;"></div> </div> <script> async function exportCsv() { const sheetName = document.getElementById('sheetName').value.trim(); const errorDiv = document.getElementById('error'); errorDiv.textContent = ''; if (!sheetName) { errorDiv.textContent = '请输入工作表名称'; return; } try { // 调用后端脚本,传入工作表名称 const response = await google.script.run.withSuccessHandler(handleSuccess).withFailureHandler(handleError).exportSheetToCsv(sheetName); } catch (err) { errorDiv.textContent = err.message; } } function handleSuccess(data) { // 创建下载链接并触发下载 const a = document.createElement('a'); a.href = `data:text/csv;base64,${data.data}`; a.download = data.filename; a.click(); } function handleError(err) { document.getElementById('error').textContent = err.message; } </script> </body> </html>
关键修改点:
- 新增
sheetName输入框,让用户指定要导出的工作表 - 修改
exportCsv函数,将输入的工作表名称传递给后端exportSheetToCsv函数 - 完善错误提示逻辑,告知用户工作表不存在或未输入名称的情况
三、使用方法
- 在Google Sheet中打开脚本编辑器(工具→脚本编辑器)
- 替换原有的GAS代码为上面的修改版本
- 创建名为
Index的HTML文件,粘贴上面的HTML代码 - 部署Web应用(发布→部署为Web应用),根据需求设置访问权限
- 访问部署后的URL,输入要导出的工作表名称,点击导出即可
内容的提问来源于stack exchange,提问作者xyz333
相关产品推荐
相关产品推荐

