使用C#和Sheets API v4更新Cell
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用C#和Sheets API v4更新Cell相关的知识,希望对你有一定的参考价值。
有没有人有一个很好的C#示例用于使用v4 API更新单元格?
我在使用Google表格API v4的开发者网站上获得了获取单元格值c#示例。我试图修改示例以更新值为“Tom”的单元格。我坚持使用SpreadSheets.Values.Update
的设置。
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.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GoogleSheetsAPI4_v1console
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.Spreadsheet };
static string ApplicationName = "TestSpreadsheet";
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 = "<<myspreadsheetid>>";
String range = "Sheet1!D5"; // single cell D5
String myNewCellValue = "Tom";
SpreadsheetsResource.ValuesResource.UpdateRequest request = service.Spreadsheets.Values.Update(<<what goes here?>>, 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;
Console.WriteLine(values);
}
}
}
这是一个使用控制台编写单个单元格的工作示例。谢谢大家的帮助!!
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.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GoogleSheetsAPI4_v1console
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.Spreadsheets}; // static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "<MYSpreadsheet>";
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);
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,
});
String spreadsheetId2 = "<my spreadsheet ID>";
String range2 = "<my page name>!F5"; // update cell F5
ValueRange valueRange = new ValueRange();
valueRange.MajorDimension = "COLUMNS";//"ROWS";//COLUMNS
var oblist = new List<object>() { "My Cell Text" };
valueRange.Values = new List<IList<object>> { oblist };
SpreadsheetsResource.ValuesResource.UpdateRequest update = service.Spreadsheets.Values.Update(valueRange, spreadsheetId2, range2);
update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
UpdateValuesResponse result2 = update.Execute();
Console.WriteLine("done!");
}
}
}
我想您只是有权阅读您的表格,因为我可以看到:
static string [] Scopes = {SheetsService.Scope.Spreadsheet Readonly};
尝试通过“SheetsService.Scope.Spreadsheet”或“SheetsService.Scope.Drive”更改“SheetsService.Scope.SpreadsheetsReadonly”。也许这是另一种语法......如果这不是授权问题,我无法帮助你,对不起......祝你好运我的朋友。
Ps:在Xcode(objective-c)上,你必须在修改范围后重置模拟器。对你(C#)我不知道。
如果您正在使用本教程https://developers.google.com/sheets/quickstart/dotnet确保您注释掉以下代码行。
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
这也是我使用语法并使其工作的原因。
String spreadsheetId2 = "<put yours here>";
String range2 = "<againyours>!F5";
ValueRange valueRange = new ValueRange();
valueRange.MajorDimension = "COLUMNS";//"ROWS";//COLUMNS
var oblist = new List<object>() { "ello" };
valueRange.Values = new List<IList<object>> { oblist };
SpreadsheetsResource.ValuesResource.UpdateRequest update = service.Spreadsheets.Values.Update(valueRange, spreadsheetId2, range2);
update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
UpdateValuesResponse result2 = update.Execute();
文件“Google.Apis.Sheets.v4.SpreadsheetsResource.cs”包含错误:url“https://sheets.googleapis.com/v4/spreadsheets/ {spreadsheetId} / values / {range}”不包含“?valueInputOption = RAW”。暂时使用此代码:
String spreadsheetId = "rihhgfkjhgufhgHUGUJKGHUItgUIGUIgui";
String range = "Config!A2:E";
ValueRange valueRange=new ValueRange();
valueRange.Range = range;
valueRange.MajorDimension = "ROWS";//"ROWS";//COLUMNS
var oblist=new List<object>(){12,3,4,5u,6};
valueRange.Values = new List<IList<object>> {oblist};
var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}?valueInputOption=RAW".Replace("{spreadsheetId}",spreadsheetId).Replace("{range}", HttpUtility.UrlEncode(range));
JObject json = null;
using (var client = new WebClient())
{
client.Headers.Set("Authorization", "Bearer " + credential.Token.AccessToken);
client.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
client.Headers.Set(HttpRequestHeader.UserAgent, "myprogram database updater google-api-dotnet-client/1.13.1.0 (gzip)");
ServicePointManager.Expect100Continue = false;
var jsonstr = JsonConvert.SerializeObject(valueRange);
var jsontemp = JObject.Parse(jsonstr);
jsontemp.Remove("ETag");
jsonstr = jsontemp.ToString();
try
{
var res = client.UploadString(url, "PUT", jsonstr);
json = JObject.Parse(res);
}
catch (Exception)
{
}
}
首先创建值范围对象,如下所示:
Google.Apis.Sheets.v4.Data.ValueRange requestBody = new Google.Apis.Sheets.v4.Data.ValueRange();
以上是关于使用C#和Sheets API v4更新Cell的主要内容,如果未能解决你的问题,请参考以下文章
使用 Sheets API v4 Java 阅读整个 Google 电子表格
如何使用 Google Sheets API V4 导入 CSV 文件
使用Sheets API v4获取与Google帐户关联的所有电子表格列表
Google Sheets API v4 - 如何获得最后一行的价值?