未登录状态下使用C# WPF+Google Sheets API无法访问表格数据
解决方案:无需登录访问Google Sheets + 解决跨机器启动问题
首先,你的核心问题有两个:一是当前代码依赖用户登录Google账号才能访问数据,二是编译后其他机器无法启动应用。我分别给你解决思路和修改后的代码:
1. 改用服务账号实现无用户登录访问
你现在用的GoogleWebAuthorizationBroker是针对个人用户授权的流程,必须用户登录。要让应用独立访问表格,应该用Google服务账号——这是专门给应用使用的身份,不需要用户交互。
前置步骤:
- 登录Google Cloud Console,找到你的项目,创建一个服务账号,下载对应的JSON密钥文件(比如命名为
service-account-key.json) - 打开你的Google Sheets表格,点击右上角「分享」,把服务账号的邮箱(密钥文件里的
client_email字段)添加进去,权限设为「查看者」或「编辑者」 - 修改代码,用服务账号认证替代原来的用户授权逻辑
2. 解决跨机器启动失败的问题
你的代码里直接把文件下载到根目录"\client_secret.json",这在大多数Windows机器上会因为权限不足导致写入失败,而且路径写法不规范。另外,要确保编译时把Google API的依赖库一起打包给用户。
修改后的完整代码:
using Google.Apis.Auth.OAuth2; using Google.Apis.Sheets.v4; using Google.Apis.Services; using System; using System.IO; namespace GoogleSheetsAccess { class Program { static string ApplicationName = "Your App Name"; // 替换成你的服务账号密钥文件路径(打包到应用目录,用相对路径更可靠) static string ServiceAccountKeyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "service-account-key.json"); static string SpreadsheetId = "1uLxm0jvmL1_FJNYUJp6YqIezzqrZdjPf2xQGOWYd6ao"; static string Range = "TestSheet!A1:F"; static void Main(string[] args) { try { // 服务账号认证逻辑 GoogleCredential credential; using (var stream = new FileStream(ServiceAccountKeyPath, FileMode.Open, FileAccess.Read)) { // 只读权限用SpreadsheetsReadonly,需要编辑就换成Spreadsheets credential = GoogleCredential.FromStream(stream) .CreateScoped(SheetsService.Scope.SpreadsheetsReadonly); } // 创建Sheets服务实例 var service = new SheetsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = ApplicationName }); // 请求并获取表格数据 var request = service.Spreadsheets.Values.Get(SpreadsheetId, Range); var response = request.Execute(); var values = response.Values; if (values != null && values.Count > 0) { Console.WriteLine("获取到表格数据:"); foreach (var row in values) { Console.WriteLine(string.Join(", ", row)); } } else { Console.WriteLine("未找到任何数据。"); } } catch (Exception ex) { Console.WriteLine($"运行出错:{ex.Message}"); Console.WriteLine(ex.StackTrace); } Console.ReadLine(); } } }
额外注意事项:
- 把服务账号密钥文件
service-account-key.json放到应用的输出目录,编译时一起打包给用户,不要远程下载(既不安全又容易出问题) - 如果是.NET Framework项目,要把
Google.Apis.Sheets.v4.dll、Google.Apis.Auth.dll等依赖DLL一起发给用户;如果是.NET Core/.NET 6+,可以用dotnet publish -c Release -r win-x64 --self-contained true生成包含所有依赖的单文件包
内容的提问来源于stack exchange,提问作者Sheepsaurus
相关产品推荐
相关产品推荐

