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

Google Apps Script生成图表时遇空数据表错误求助

解决Google Apps Script图表生成时“空数据表”错误的方案

问题描述

我使用Google Apps Script编写脚本,将电子表格中的测试结果生成PDF格式报告。脚本逻辑看似正确,但每次运行都会返回错误:
"Exception: Cannot create a chart with an empty data table."

错误原因

  1. 数据类型不匹配:你定义的图表数据列是NUMBER类型,但formatAsPercentage函数返回的是带百分号的字符串(如"75%"),导致数据行无法被正确添加到数据表,最终数据表为空。
  2. 潜在数据无效:电子表格对应单元格可能存在空值、非数字值,也会导致数据行添加失败。

修复步骤

1. 修正百分比格式化逻辑(核心修复)

将formatAsPercentage改为返回数字类型,图表的百分比显示通过轴格式设置实现,而非修改数据本身:

// 修正后的百分比格式化函数:返回0-100的数字,确保数据类型匹配
function formatAsPercentage(value) {
  // 处理非数字情况,避免报错
  const numValue = typeof value === 'number' && !isNaN(value) ? value : 0;
  return numValue * 100;
}

2. 给图表添加百分比轴格式

在图表构建代码中,添加Y轴的百分比显示配置:

const chartBuilder = Charts.newComboChart()
    .setDataTable(dataTable)
    .setDimensions(600, 400)
    .setRange(0, 100) // 对应0-100的数字范围
    .setSeries([{
        type: Charts.ChartType.BARS,
        targetAxisIndex: 0,
        color: '#7B70AD'
    }, {
        type: Charts.ChartType.LINE,
        targetAxisIndex: 0,
        color: '#B46AAB'
    }, {
        type: Charts.ChartType.STEPPED_AREA,
        targetAxisIndex: 0,
        color: '#D8D5E7'
    }])
    .setLegendPosition(Charts.Position.BOTTOM)
    // 新增:设置Y轴显示为百分比格式
    .setYAxisTitle('得分百分比')
    .setYAxisFormat('#%');

3. 校验数据有效性(可选但推荐)

在添加数据行前,检查每个分数是否为有效数字,避免无效数据导致数据表为空:

for(let i = 0; i < candidateScoresIndices.length; i++) {
  // 提取并校验每个分数
  const candidateScore = typeof row[candidateScoresIndices[i]] === 'number' ? row[candidateScoresIndices[i]] : 0;
  const topQuintileScore = typeof row[topQuintileIndices[i]] === 'number' ? row[topQuintileIndices[i]] : 0;
  const medianScore = typeof row[medianIndices[i]] === 'number' ? row[medianIndices[i]] : 0;
  
  // 添加有效数据行
  dataTable.addRow([
    skillNames[i], 
    formatAsPercentage(candidateScore), 
    formatAsPercentage(topQuintileScore), 
    formatAsPercentage(medianScore)
  ]);
}

额外检查点

  • 确认电子表格中candidateScoresIndices、topQuintileIndices、medianIndices对应的列(如第5列、第8列等)为数字格式,无文本或空值。
  • 查看脚本日志(Logger输出),确认Candidate Scores、Top Quintile、Median对应的数值都是有效数字,没有undefined或空字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:37:03