以下介紹如何使用Google Sheets API 讀取Google Spreadsheet,Google Sheets API 支援很多語言,如Go、JAVA、JavaScript、.NET、Node.js、PHP、Python、Ruby等,可參考Google的線上文件:Introduction to the Google Sheets API,筆者使用C#與Google Sheets API V4版來開發應用程式。
Step 1. Visual Studio 2010或更高的版本,建立一個C# Console專案。
Step 2. 安裝NuGet,用NuGet Package Manager安裝Google.Apis.Sheets.v4套件。
VS2010
VS2013
PM > Install-Package Google.Apis.Sheets.v4
PS:取得 NuGet in Visual Studio
* Visual Studio 2012 後的版本,已內建 NuGet 了,不用額外安裝。
* Visual Studio 2010 沒有內建 NuGet,需要先手動下載並安裝。參考 NuGet Download
Step 3. 下載申請好的Google OAuth憑證,更名為client_secret.json,可參考 建立Google OAuth 2.0 憑證,並將 client_secret.json 加入專案中。
Step 4. 設定 client_secret.json 屬性,將Copy to Output Directory 設為Copy always。
VS2010
VS2013
使用以下程式編譯
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.IO;
using System.Threading;
using System.Threading.Tasks;
namespace GoogleSheet
{
class Program
{
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
//應用程式的名字需要英文
static string ApplicationName = "Get Google SheetData with Google Sheets API";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.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 = "1SyfODMfB1t7kpZ-CscOUIXdl6wHoHwYsxIjsbzMfzSk";
String range = "商品名稱!A1:C4";
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/1SyfODMfB1t7kpZ-CscOUIXdl6wHoHwYsxIjsbzMfzSk/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
foreach (var col in row)
{
Console.Write("{0} ", col);
}
Console.WriteLine();
//或是以下寫法
//Console.WriteLine("{0}, {1}, {2}", row[0], row[1], row[2]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
}
}
spreadsheetId取得
第一次存取Google sheet資料,Google會要求授權同意,之後就不會再出現授權畫面了。
執行畫面
參考資料
- 建立Google OAuth 2.0 憑證
- .NET Quickstart
- 使用NuGet安裝、移除、更新套件
- [.NET]如何取得 Google Spreadsheet 中各個 sheet 資訊
- 價格追蹤:使用 gspread 自動更新 Google Sheets
其他參考資料
- OAuth 2.0 for Google Apps Service Accounts (installed and web applications)
- Google OAuth 2.0 Service Account Impersonate Personal Account
- 利用C#對Google Spreadsheet進行線上即時存取
- c# - Google.GData.Client.GDataRequestException - Authentication suddenly fails in old code
- SpreadSheet API with .NET:How to add new row into Google SpreadSheet?
- Google Sheets with C#
- Google.GData.Client.GDataRequestException - Authentication suddenly fails in old code









