You need to enable JavaScript to run this app. 使用API密钥而非OAuth2调用Google Sheets API的C#实现报错求助
优惠活动
大模型
产品
解决方案
定价
更多

使用API密钥而非OAuth2调用Google Sheets API的C#实现报错求助

错误原因

当前抛出的参数错误是因为你设置的ApplicationName值@Timetable包含了不被Google API客户端库允许的特殊字符@,该参数仅支持字母、数字、短横线、下划线、空格等常规字符。

完整实现流程
  • 首先安装Google Sheets API的C#客户端依赖,可通过NuGet包管理器安装Google.Apis.Sheets.v4,或使用dotnet CLI执行命令:
    dotnet add package Google.Apis.Sheets.v4
  • 前置条件确认:
    • 你使用的API密钥已经在Google Cloud控制台为所属项目开启了Google Sheets API权限
    • 目标Google表格已设置为「任何拥有链接的人都可查看」,API密钥属于匿名鉴权凭证,无法访问非公开的表格
  • 编写正确的调用代码,示例如下:
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using System.Collections.Generic;

public class SheetsApiService
{
    // 修正应用名称,移除特殊字符@
    static string ApplicationName = "Timetable";
    // 替换为你自己的有效API密钥
    private static readonly string API_KEY = "你的实际API密钥";
    // 替换为目标表格的ID
    static readonly string spreadsheetId = "你的实际表格ID";

    public List<string> GetSheetNames()
    {
        // 初始化Sheets服务
        var service = new SheetsService(new BaseClientService.Initializer()
        {
            ApplicationName = ApplicationName,
            ApiKey = API_KEY,
        });

        // 发起获取表格元数据的请求
        var ssRequest = service.Spreadsheets.Get(spreadsheetId);
        Spreadsheet ss = ssRequest.Execute();

        // 提取所有Sheet的名称返回
        List<string> sheetList = new List<string>();
        foreach (var sheet in ss.Sheets)
        {
            sheetList.Add(sheet.Properties.Title);
        }

        return sheetList;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 05:36:09