前置作業
[C# + Google SpreadSheet] (一)、建立Google OAuth 2.0
[C# + Google SpreadSheet] (二)、讀取Google SpreadSheet內容
[C# + Google SpreadSheet] (三)、更新寫入Google SpreadSheet內容
參考資料
Google Sheets API v4 使用 C# (3) --- 添加寫入 Google Spreadsheet
範例程式
static void AppendRow(SheetsService service)
{
string[] Scopes = { SheetsService.Scope.Spreadsheets, SheetsService.Scope.Drive };
//應用程式的名字需要英文
string ApplicationName = "Get Google SheetData with Google Sheets API";
//輸出檔名稱Ex."client_secret.json"
string JsonName = "client_secret.json";
//spreadsheetId,為google spreadsheet的網址 : / d / XXXXX /
//Ex: https://docs.google.com/spreadsheets/d/1kLk9VslDYn0nhZpJZXd3tErt1f2gzG-2eSJWbrh2piU/edit#gid=0
string spreadsheetId = "1kLk9VslDYn0nhZpJZXd3tErt1f2gzG-2eSJWbrh2piU";
//頁籤名稱
string sheetName = "test";
//選取範圍
String range = sheetName + "!A1";
UserCredential credential;
using (var stream = new FileStream(JsonName, FileMode.Open, FileAccess.Read))
{
string credPath = Path.Combine
(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
".credentials/sheets.googleapis.com-dotnet-quickstart.json");
//存儲憑證到credPath
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
//建立一個API服務,設定請求參數
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
List<object> list1 = new List<object>() { "Item" , "A" , "B" , "C" };
List<object> list2 = new List<object>() { "國文" ,"90" , "65" , "100" };
List<object> list3 = new List<object>() { "英文" ,"80" , "32" , "50" };
List<object> list4 = new List<object>() { "數學" ,"70" , "99" , "10" };
List<object> list5 = new List<object>() { "總分" ,"=SUM(B2:B4)", "=SUM(C2:C4)" , "=SUM(D2:D4)" };
IList<IList<Object>> list = new List<IList<Object>>() { list1, list2, list3, list4, list5 };
ValueRange VRange = new ValueRange();
VRange.Range = range;
VRange.Values = list;
SpreadsheetsResource.ValuesResource.AppendRequest upd
= service.Spreadsheets.Values.Append(VRange, spreadsheetId, range);
upd.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
AppendValuesResponse responses = upd.Execute();
}
版主你好:
回覆刪除根據你的教學步驟,在最後一行會出現錯誤告知沒有權限的問題?想請問怎麼解決?
另外,若我想將雲端excel的資料透過DataGridView排列顯示好,請問需要怎麼修改呢?
希望板主可以幫忙解決,謝謝!
權限問題可參考版主第三篇文章, 有寫解法
回覆刪除