You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script中getValues()获取含日期范围返回null的问题

问题:Google Sheets脚本通过google.script.run传递含日期的getValues()结果返回null

问题现象

  • 获取含日期值(如2000-01-01)的命名范围数据时,后端Google Apps Script中调用getValues()能在日志中正常输出结果,但通过google.script.run传递到自定义侧边栏前端时,接收到的是null
  • 使用getDisplayValues()可正常返回数据,但该方法返回的是格式化后的字符串,无法满足获取精确未格式化值的需求
  • 移除范围中的日期值、对getValues()结果执行JSON.stringify()处理后,数据能正常传递到前端

后端脚本示例

function gsExplorationData(){
    var range=SpreadsheetApp.getActiveSpreadsheet().getRangeByName('MyNamedRange');
    Logger.log({'range.getValues()': range.getValues()});
    return {'range.getValues()': range.getValues()}
}

侧边栏前端脚本示例

dataSubmit(){
  google.script.run.withFailureHandler(function(error){console.log('GS ERROR: '+ error.message)}).withSuccessHandler(function(gsResponse){
    console.log('gsExplorationData()',gsResponse);
  }).gsGetgsExplorationDataData() // 注意此处函数名存在拼写错误,应为gsExplorationData()
}

原因分析

这是google.script.run的预期限制:该API在跨端传递数据时不支持直接传输Date对象,当返回结果中包含Date类型时,会导致序列化失败,最终前端接收到null。官方已明确此为预期行为,暂无修改计划。

解决方案

在后端将Date对象转换为可序列化的字符串格式(如ISO 8601标准字符串),传递到前端后再转换回Date对象,即可保留精确的日期值。

修正后的后端函数

function gsExplorationData(){
    var rangeValues = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('MyNamedRange').getValues();
    // 遍历数组,将所有Date对象转为ISO字符串
    var processedData = rangeValues.map(row => 
        row.map(cell => cell instanceof Date ? cell.toISOString() : cell)
    );
    Logger.log({'processedData': processedData});
    return {'range.getValues()': processedData};
}

前端处理代码

dataSubmit(){
  google.script.run
    .withFailureHandler(error => console.log('GS ERROR: '+ error.message))
    .withSuccessHandler(gsResponse => {
        // 将ISO字符串转回Date对象
        const restoredData = gsResponse['range.getValues()'].map(row => 
            row.map(cell => {
                // 判断是否为ISO日期字符串
                if (typeof cell === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/.test(cell)) {
                    return new Date(cell);
                }
                return cell;
            })
        );
        console.log('gsExplorationData()', restoredData);
    })
    .gsExplorationData(); // 修正函数名拼写错误
}

内容的提问来源于stack exchange,提问作者Vlad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:17:10