22

有没有人有一个很好的 C# 示例来使用 v4 API 更新单元格?

我有来自使用 Google Sheets 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);
        }
    }
}
4

6 回答 6

30

这是一个使用控制台编写单个单元格的工作示例。感谢所有帮助过的人!!

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!");

        }
    }
}
于 2016-08-09T03:02:01.957 回答
1

如果您正在使用本教程 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(); 
于 2016-08-01T06:34:23.867 回答
1

文件“Google.Apis.Sheets.v4.SpreadsheetsResource.cs”包含错误:url“ https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range }”不包含“?valueInputOption=生的”。暂时使用此代码:

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)
    {


    }
}
于 2016-07-02T14:38:03.583 回答
1

对于找到此线程的其他任何人。我得到了以下异常:

异常详细信息:Google.GoogleApiException:Google.Apis.Requests.RequestError 'valueInputOption' 是必需的,但未指定 [400] 错误 [ 消息 ['valueInputOption' 是必需的,但未指定] 位置 [ - ] 原因 [badRequest] 域 [全局] ]

解决了:

SpreadsheetsResource.ValuesResource.UpdateRequest update = service.Spreadsheets.Values.Update(valueRange, spreadsheetId2, range2);
update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
UpdateValuesResponse result2 = update.Execute();

资源:

https://stackoverflow.com/a/38841369/3850405

然而,这导致我的数据在我输入的值之前得到一个单引号 ('),如下所示:

在此处输入图像描述

阅读文档后,我看到使用的示例"valueInputOption": "USER_ENTERED"

https://developers.google.com/sheets/api/samples/writing#write_to_multiple_ranges

切换到ValueInputOptionEnum.USERENTERED一切按预期工作后。

updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
于 2020-08-19T14:30:10.527 回答
0

我认为您只能阅读您的工作表,因为我可以看到:

静态字符串 [] 范围 = { SheetsService.Scope.SpreadsheetsReadonly };

尝试通过“SheetsService.Scope.Spreadsheet”或“SheetsService.Scope.Drive”更改“SheetsService.Scope.SpreadsheetsReadonly”。也许这是另一种语法...如果不是授权问题,我无法帮助您,对不起...祝我的朋友好运。

Ps:在Xcode(objective-c)上,修改范围后必须重置模拟器。对于你(C#)我不知道。

于 2016-06-05T19:00:03.593 回答
0

首先创建值范围对象,如下所示:

Google.Apis.Sheets.v4.Data.ValueRange requestBody = new Google.Apis.Sheets.v4.Data.ValueRange();
于 2018-09-20T11:33:00.663 回答