[英]Accessing Google Spreadsheets with C# using Google Data API
我在 Google 電子表格中將一些信息作為單個工作表。 有什么方法可以通過提供 google 憑據和電子表格地址從 .NET 讀取此信息。 是否可以使用 Google 數據 API。 最終,我需要從 DataTable 中的 Google 電子表格中獲取信息。 我該怎么做? 如果有人嘗試過,請分享一些信息。
根據.NET 用戶指南:
下載.NET 客戶端庫:
添加這些 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);
}
給定您已經檢索到的電子表格條目,您可以獲得此電子表格中所有工作表的列表,如下所示:
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);
}
我圍繞Google 的 .Net 客戶端庫編寫了一個簡單的包裝器,它公開了一個更簡單的類似數據庫的界面,具有強類型記錄類型。 這是一些示例代碼:
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 的結構化查詢運算符:
var q = from r in table.AsQueryable()
where r.IntProp > -1000 && r.StringProp == "hello"
orderby r.IntProp
select r;
(2016 年 6 月至 11 月)該問題及其答案現已過時,因為:1) GData API是上一代 Google API。 雖然並非所有 GData API 都已棄用,但所有最新的 Google API都不使用Google 數據協議; 2) 有一個新的 Google Sheets API v4 (也不是 GData)。
從這里開始,您需要獲取適用於 .NET 的 Google API 客戶端庫並使用最新的Sheets API ,它比任何以前的 API 都更加強大和靈活。 這是幫助您入門的C# 代碼示例。 另請查看Sheets API的.NET 參考文檔和.NET Google API 客戶端庫開發人員指南。
如果您對 Python 不過敏(如果您是,請假裝它是偽代碼;)),我制作了幾個視頻,其中包含更長、更“真實”的 API 使用示例,您可以從中學習並遷移到 C#(如果需要) :
這個由 Marcos Placona 於 2017 年 3 月 24 日創建的 Twilio 博客頁面可能會有所幫助。
它引用了Google.Api.Sheets.v4和OAuth2 。
您可以通過以下幾種方式完成您的要求:
使用 Google 的電子表格 C# 庫(如 Tacoman667 的回答)來獲取一個 ListFeed,它可以返回一個行列表(Google 用語是 ListEntry),每個行都有一個名稱-值對列表。 Google 電子表格 API ( http://code.google.com/apis/spreadsheets/code.html ) 文檔提供的信息足以讓您入門。
使用 Google 可視化 API,您可以提交更復雜的(幾乎類似於 SQL)查詢以僅獲取所需的行/列。
電子表格內容作為 Atom 提要返回,因此您可以使用 XPath 或 SAX 解析來提取列表提要的內容。 在http://gqlx.twyst.co.za有一個這樣做的例子(雖然我很害怕,但只有在 Java 和 Javascript 中)。
正如@wescpy 所說,@Kelly 最受好評的答案不再有效。 但是,在 2020-03-03 之后,它根本無法工作,因為所使用的庫使用Google Sheets v3 API
。
Google Sheets v3 API 將於 2020 年 3 月 3 日關閉
https://developers.google.com/sheets/api/v3
這是谷歌在 2019-09-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();
}
}
}
http://code.google.com/apis/gdata/articles/dotnet_client_lib.html
這應該讓你開始。 我最近沒有玩過它,但不久前我下載了一個非常舊的版本,它看起來很可靠。 這個也更新到了 Visual Studio 2008,所以請查看文檔!
我很確定谷歌代碼上會有一些 C# SDK/工具包。 我找到了這個,但可能還有其他的,所以值得瀏覽一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.