使用C#和Sheets API v4更新Cell

时间:2016-05-26 13:53:16

标签: c# google-sheets google-api google-sheets-api google-api-dotnet-client

有没有人有一个很好的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);
        }
    }
}

6 个答案:

答案 0 :(得分:22)

这是一个使用控制台编写单个单元格的工作示例。谢谢大家帮忙!!

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

        }
    }
}

答案 1 :(得分:0)

我认为你可以阅读你的表格,因为我可以看到:

  

static string [] Scopes = {SheetsService.Scope.SpreadsheetsReadonly};

尝试更改&#34; SheetsService.Scope.SpreadsheetsReadonly&#34; by&#34; SheetsService.Scope.Spreadsheet&#34;或者通过&#34; SheetsService.Scope.Drive&#34;。也许它是另一种语法......如果它不是授权问题我无法帮助你,对不起......祝你好运我的朋友。

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

答案 2 :(得分:0)

文件&#34; Google.Apis.Sheets.v4.SpreadsheetsResource.cs&#34;包含错误:网址&#34; https://sheets.googleapis.com/v4/spreadsheets/ {spreadsheetId} / values / {range}&#34;不包含&#34;?valueInputOption = RAW&#34;。暂时使用此代码:

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


    }
}

答案 3 :(得分:0)

如果您正在使用本教程 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(); 

答案 4 :(得分:0)

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

Google.Apis.Sheets.v4.Data.ValueRange requestBody = new Google.Apis.Sheets.v4.Data.ValueRange();

答案 5 :(得分:0)

对于其他找到此线程的人。我在下面遇到了异常:

异常详细信息: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

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

enter image description here

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

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

切换到ValueInputOptionEnum.USERENTERED后,一切正常。

updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;