Dostęp do arkuszy kalkulacyjnych Google za pomocą C# przy użyciu Google Data API
Mam pewne informacje w arkuszach kalkulacyjnych Google jako pojedynczy arkusz. Czy jest jakiś sposób, w jaki mogę odczytać te informacje z. NET, podając dane uwierzytelniające google i adres arkusza kalkulacyjnego. Czy jest to możliwe przy użyciu interfejsów API danych Google. Ostatecznie muszę uzyskać informacje z arkusza kalkulacyjnego Google w DataTable. Jak mogę to zrobić? Jeśli ktoś próbował, pls udostępniają pewne informacje.
8 answers
Zgodnie z . net user guide :
Pobierz . Net client library :
Dodaj te wyrażenia używając:
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;
Uwierzytelnienie:
SpreadsheetsService myService = new SpreadsheetsService("exampleCo-exampleApp-1");
myService.setUserCredentials("[email protected]", "mypassword");
Pobierz listę arkuszy kalkulacyjnych:
SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = myService.Query(query);
Console.WriteLine("Your spreadsheets: ");
foreach (SpreadsheetEntry entry in feed.Entries)
{
Console.WriteLine(entry.Title.Text);
}
Biorąc pod uwagę już pobrany arkusz kalkulacyjny, możesz uzyskać listę wszystkich arkuszy w tym arkuszu kalkulacyjnym w następujący sposób:
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);
}
I uzyskać kanał oparty na komórce:
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);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-14 02:39:00
Napisałem prosty wrapper wokół biblioteki klienta Google.Net, eksponuje prostszy interfejs podobny do bazy danych, z silnie wpisanymi typami rekordów. Oto przykładowy kod:
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("[email protected]", "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);
Istnieje również dostawca LINQ, który tłumaczy się na operatory zapytań strukturalnych google :
var q = from r in table.AsQueryable()
where r.IntProp > -1000 && r.StringProp == "hello"
orderby r.IntProp
select r;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-11 03:52:35
(Czerwiec-Listopad 2016) pytanie i odpowiedzi na nie są obecnie nieaktualne: 1) GData API są poprzednią generacją Google API. Chociaż nie wszystkie API GData zostały przestarzałe, Wszystkie najnowsze API Google nie używają protokół danych Google; i 2) istnieje Nowy interfejs API Arkuszy Google v4 (również nie GData).
Idąc dalej, musisz uzyskać bibliotekę klienta API Google dla. Net i korzystać z najnowszej Sheets API , który jest znacznie bardziej wydajny i elastyczny niż poprzednie API. Oto przykład kodu C# , który pomoże Ci zacząć. Sprawdź również . NET reference docs dla arkuszy API i . Net Google API Client Library developers guide.
Jeśli nie jesteś uczulony na Python (Jeśli jesteś, po prostu udawaj, że to pseudokod ;)), zrobiłem kilka filmów z nieco dłuższymi, bardziej "realnymi" przykładami korzystania z API, z których możesz się uczyć i migrować do C# w razie potrzeby:
- Migracja danych SQL do arkusza (code deep dive post)
- formatowanie tekstu za pomocą arkuszy API (code deep dive post)
- generowanie slajdów z danych arkusza kalkulacyjnego (code deep dive post )
- te i inne w Sheets API video library
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-05 23:12:12
Możesz zrobić to, o co prosisz na kilka sposobów:
Korzystanie z biblioteki C# arkusza kalkulacyjnego Google (jak w odpowiedzi Tacoman667) do pobrania ListFeed, który może zwrócić listę wierszy (ListEntry w Google parlance), z których każdy ma listę par nazwa-wartość. Google spreadsheet API ( http://code.google.com/apis/spreadsheets/code.html ) dokumentacja zawiera więcej niż wystarczająco dużo informacji, aby zacząć.
Korzystanie z interfejsu Google visualization API, który umożliwia wyślij bardziej zaawansowane (prawie jak SQL) zapytania, aby pobrać tylko wiersze/kolumny, których potrzebujesz.
Zawartość arkusza kalkulacyjnego jest zwracana jako kanały Atom, więc możesz użyć parsowania XPath lub SAX do wyodrębnienia zawartości kanału list. Jest przykład zrobienia tego w ten sposób (tylko w Javie i Javascript, choć obawiam się) na http://gqlx.twyst.co.za.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-04 13:36:42
To, co robimy, jest dla nas bardzo ważne.
Arkusze kalkulacyjne Google i. NET Core
Odwołuje się do Google.Api.Prześcieradła.v4 i OAuth2 .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-04 12:38:05
Http://code.google.com/apis/gdata/articles/dotnet_client_lib.html
To powinno zacząć. Nie grałem z nim ostatnio, ale pobrałem bardzo starą wersję jakiś czas temu i wydawało się całkiem solidne. Ten jest również zaktualizowany do Visual Studio 2008, więc sprawdź dokumenty!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-04 12:59:13
Najbardziej upvoted odpowiedź od @ Kelly nie jest już ważna, jak mówi @ wescpy. Jednak po 2020-03-03 w ogóle nie będzie działać, ponieważ używana biblioteka używa Google Sheets v3 API
.
Google Sheets V3 API zostanie wyłączone 3 marca 2020 r.]}
Https://developers.google.com/sheets/api/v3
To zostało ogłoszone 2019-09-10 przez Google:
Https://cloud.google.com/blog/products/g-suite/migrate-your-apps-use-latest-sheets-api
Nowy kod próbka dla Google Sheets v4 API
:
Przejdź do
Https://developers.google.com/sheets/api/quickstart/dotnet
I wygenerować credentials.json
. Następnie zainstaluj Google.Apis.Sheets.v4
NuGet i wypróbuj następujący przykład:
Zauważ, że dostałem błąd Unable to parse range: Class Data!A2:E
z przykładowym kodem, ale z moim arkuszem kalkulacyjnym. Zmiana na Sheet1!A2:E
zadziałała jednak, ponieważ mój arkusz został tak nazwany. Również pracował tylko 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();
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-25 20:09:13
Jestem pewien, że będą jakieś C# SDK / toolkity w kodzie Google do tego. Znalazłem Ten, ale mogą być inne, więc warto się rozejrzeć.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-07 13:17:57