【问题标题】:Accessing Google Spreadsheets with C# using Google Data API使用 Google Data API 使用 C# 访问 Google 电子表格
【发布时间】:2010-10-18 01:25:06
【问题描述】:

我在 Google 电子表格中将一些信息作为单张表格保存。 有什么方法可以通过提供谷歌凭据和电子表格地址从.NET 读取这些信息。是否可以使用 Google 数据 API。 最终,我需要从 DataTable 中的 Google 电子表格中获取信息。 我该怎么做?如果有人尝试过,请分享一些信息。

【问题讨论】:

标签: c# google-sheets google-api-dotnet-client google-data-api google-sheets-api


【解决方案1】:

(2016 年 6 月至 11 月) 该问题及其答案现已过时:1) GData APIs 是上一代 Google API。虽然并非所有 GData API 都已被弃用,但all the latest Google APIs使用the Google Data Protocol; 2)有一个new Google Sheets API v4(也不是GData)。

从这里开始,您需要获取the Google APIs Client Library for .NET 并使用最新的Sheets API,它比以前的任何API 都更加强大和灵活。这是一个C# code sample,可以帮助您入门。还要检查.NET reference docs for the Sheets API.NET Google APIs Client Library developers guide

如果您对 Python 不过敏(如果您对 Python 过敏,就假装它是伪代码;)),我制作了几个视频,其中包含稍长一些、更“真实”的使用 API 的示例,您可以从中学习并迁移到C# 如果需要:

【讨论】:

  • 这些工具也可以用来访问 Microsoft Excel 文件吗?
  • 不幸的是,微软和谷歌都在制造不符合共同标准的竞争产品,因此您必须找到自己的工具来访问 Excel 文件。如果您是 Python 开发人员,请查看python-excel.org。对于其他语言,您必须搜索它们各自的社区。或者,您可以将 Excel 文件导入 Google(使用 Drive API),然后使用 Sheets API 执行您想要的操作。 Google API 支持多种语言...请参阅 developers.google.com/api-client-library
【解决方案2】:

@Kelly 最赞成的答案不再像@wescpy 所说的那样有效。但是,在 2020-03-03 之后,由于使用的库使用 Google Sheets v3 API,它将根本无法工作。

Google Sheets v3 API 将于 2020 年 3 月 3 日关闭

https://developers.google.com/sheets/api/v3

这是 Google 于 2019 年 9 月 10 日宣布的:

https://cloud.google.com/blog/products/g-suite/migrate-your-apps-use-latest-sheets-api

Google Sheets v4 API 的新代码示例:

前往

https://developers.google.com/sheets/api/quickstart/dotnet

并生成credentials.json。然后安装Google.Apis.Sheets.v4 NuGet 并尝试以下示例:

请注意,我在示例代码中收到错误 Unable to parse range: Class Data!A2:E,但在我的电子表格中。但是,更改为 Sheet1!A2:E 有效,因为我的工作表就是这样命名的。也只使用了A2:E

using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace SheetsQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
        static string ApplicationName = "Google Sheets API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define request parameters.
            String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
            String range = "Class Data!A2:E";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            // Prints the names and majors of students in a sample spreadsheet:
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
            ValueRange response = request.Execute();
            IList<IList<Object>> values = response.Values;
            if (values != null && values.Count > 0)
            {
                Console.WriteLine("Name, Major");
                foreach (var row in values)
                {
                    // Print columns A and E, which correspond to indices 0 and 4.
                    Console.WriteLine("{0}, {1}", row[0], row[4]);
                }
            }
            else
            {
                Console.WriteLine("No data found.");
            }
            Console.Read();
        }
    }
}

【讨论】:

  • 如何避免指定客户端 ID/秘密和范围?我已经完成了 OAuth 流程并拥有访问令牌和刷新令牌(想想离线模式),我不想要任何这些额外的废话。我无权访问客户端 ID 和客户端密码,因为它们位于 oauth 中继服务器上,而我在后台服务中也无权访问。
  • @BlakeNiemyjski 直接使用其余API,链接:developers.google.com/sheets/api/reference/rest
  • 祝你好运尝试做任何事情,比如插入一行。我一直在寻找可以在 c# 中完成的事情,而不是这种完全令人困惑的脚本语言或其他任何东西。
【解决方案3】:

这个由 Marcos Placona 于 2017 年 3 月 24 日制作的 Twilio 博客页面可能会有所帮助。

Google Spreadsheets and .NET Core

它引用了Google.Api.Sheets.v4OAuth2

【讨论】:

    【解决方案4】:

    根据.NET user guide

    下载.NET client library:

    添加这些 using 语句:

    using Google.GData.Client;
    using Google.GData.Extensions;
    using Google.GData.Spreadsheets;
    

    验证:

    SpreadsheetsService myService = new SpreadsheetsService("exampleCo-exampleApp-1");
    myService.setUserCredentials("jo@gmail.com", "mypassword");
    

    获取电子表格列表:

    SpreadsheetQuery query = new SpreadsheetQuery();
    SpreadsheetFeed feed = myService.Query(query);
    
    Console.WriteLine("Your spreadsheets: ");
    foreach (SpreadsheetEntry entry in feed.Entries)
    {
        Console.WriteLine(entry.Title.Text);
    }
    

    给定您已经检索到的 SpreadsheetEntry,您可以获得此电子表格中所有工作表的列表,如下所示:

    AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);
    
    WorksheetQuery query = new WorksheetQuery(link.HRef.ToString());
    WorksheetFeed feed = service.Query(query);
    
    foreach (WorksheetEntry worksheet in feed.Entries)
    {
        Console.WriteLine(worksheet.Title.Text);
    }
    

    并获得基于单元格的提要:

    AtomLink cellFeedLink = worksheetentry.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);
    
    CellQuery query = new CellQuery(cellFeedLink.HRef.ToString());
    CellFeed feed = service.Query(query);
    
    Console.WriteLine("Cells in this worksheet:");
    foreach (CellEntry curCell in feed.Entries)
    {
        Console.WriteLine("Row {0}, column {1}: {2}", curCell.Cell.Row,
            curCell.Cell.Column, curCell.Cell.Value);
    }
    

    【讨论】:

    • new SpreadsheetsService("exampleCo-exampleApp-1") 的字符串值应该使用什么?我放在那里重要吗?谢谢!
    • 获取电子表格列表:“SpreadsheetQuery query = new SpreadsheetQuery();”应阅读“SpreadsheetFeed feed = myService.Query(query);”尝试编辑的字符不够多!
    • developers.google.com/google-apps/spreadsheets/authorize 重要提示:OAuth 1.0 不再受支持,将于 2015 年 5 月 5 日禁用。如果您的应用程序使用 OAuth 1.0,您必须迁移到 OAuth 2.0,否则您的应用程序将停止运行。
    • 此链接来自下面的@wescpy,帮助我找到了 2016 年中期的更多相关信息:googleappsdeveloper.blogspot.com/2016/05/…
    • 2020-03-03 之后将无法使用,因为使用的库使用 Google Sheets v3 API cloud.google.com/blog/products/g-suite/…
    【解决方案5】:

    I wrote a simple wrapper 围绕Google's .Net client library,它公开了一个更简单的类似数据库的接口,具有强类型的记录类型。下面是一些示例代码:

    public class Entity {
        public int IntProp { get; set; }
        public string StringProp { get; set; }
    }
    
    var e1 = new Entity { IntProp = 2 };
    var e2 = new Entity { StringProp = "hello" };
    var client = new DatabaseClient("you@gmail.com", "password");
    const string dbName = "IntegrationTests";
    Console.WriteLine("Opening or creating database");
    db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName); // databases are spreadsheets
    const string tableName = "IntegrationTests";
    Console.WriteLine("Opening or creating table");
    table = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName); // tables are worksheets
    table.DeleteAll();
    table.Add(e1);
    table.Add(e2);
    var r1 = table.Get(1);
    

    还有一个 LINQ 提供程序可以转换为 google 的structured query operators

    var q = from r in table.AsQueryable()
            where r.IntProp > -1000 && r.StringProp == "hello"
            orderby r.IntProp
            select r;
    

    【讨论】:

    【解决方案6】:

    您可以通过多种方式完成您的要求:

    1. 使用 Google 的电子表格 C# 库(如 Tacoman667 的回答)获取 ListFeed,它可以返回行列表(Google 用语中的 ListEntry),每个行都有一个名称-值对列表。 Google 电子表格 API (http://code.google.com/apis/spreadsheets/code.html) 文档提供的信息足以帮助您入门。

    2. 使用 Google 可视化 API,您可以提交更复杂(几乎类似于 SQL)的查询以仅获取您需要的行/列。

    3. 电子表格内容作为 Atom 提要返回,因此您可以使用 XPath 或 SAX 解析来提取列表提要的内容。在http://gqlx.twyst.co.za 有一个这样做的例子(虽然我害怕只在 Java 和 Javascript 中)。

    【讨论】:

      【解决方案7】:

      http://code.google.com/apis/gdata/articles/dotnet_client_lib.html

      这应该可以帮助您入门。我最近没有玩过它,但不久前我下载了一个非常旧的版本,它看起来很可靠。这个也更新到了 Visual Studio 2008,所以请查看文档!

      【讨论】:

        【解决方案8】:

        我很确定 Google 代码上会为此提供一些 C# SDK/工具包。我找到了this one,但可能还有其他的,所以值得一游。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-02
          • 2011-03-27
          • 2017-01-23
          • 1970-01-01
          • 1970-01-01
          • 2014-01-15
          • 2020-10-28
          相关资源
          最近更新 更多