2016-05-26 17 views
5

Có ai có ví dụ C# tốt để cập nhật ô bằng API v4 không?Google Trang tính API v4 C# cập nhật ô

Tôi có ví dụ lấy mẫu C# ví dụ từ trang web nhà phát triển làm việc với API Google Trang tính v4. Tôi đang cố sửa đổi ví dụ để cập nhật một ô có giá trị là "Tom". Tôi bị kẹt trong cài đặt cho 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); 


     } 
    } 
} 

Trả lời

0

Tôi nghĩ rằng bạn chỉ có thể truy cập để đọc tờ của bạn bởi vì tôi có thể thấy:

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

Cố gắng thay đổi "SheetsService.Scope.SpreadsheetsReadonly" bởi "SheetsService.Scope.Spreadsheet" hoặc bằng " SheetsService.Scope.Drive ". Có lẽ đó là một cú pháp khác ... Nếu nó không phải là một vấn đề của ủy quyền tôi không thể giúp bạn, xin lỗi ... Chúc may mắn bạn tôi.

Ps: Trên Xcode (mục tiêu-c), bạn phải đặt lại trình mô phỏng sau khi sửa đổi phạm vi. Đối với bạn (C#) Tôi không biết.

+0

Bạn chính xác chắc chắn sẽ không chỉ đọc. Tôi đã thay đổi thành "SheetsService.Scope.Spreadsheet". – Slim

+0

Tôi bị mắc kẹt trên cú pháp cho Spreadsheets.Values.Update (<< những gì diễn ra ở đây? >>, spreadsheetId, phạm vi); các tham số 'bảng tính' và 'dải ô' là các chuỗi, trong khi phiên bản đầu tiên được liệt kê là cần phải là 'nội dung'. – Slim

0

Tệp "Google.Apis.Sheets.v4.SpreadsheetsResource.cs" chứa lỗi: url "https://sheets.googleapis.com/v4/spreadsheets/ {spreadsheetId}/values ​​/ {range}" không chứa "? ValueInputOption = RAW". Sử dụng mã này tạm thời:

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


    } 
} 
0

Nếu bạn đang sử dụng hướng dẫn https://developers.google.com/sheets/quickstart/dotnet này Đảm bảo bạn nhận xét ra các dòng mã sau đây.

credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json"); 

Đây cũng là những gì tôi đã sử dụng cú pháp khôn ngoan và làm cho nó hoạt động.

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(); 
+0

Cảm ơn bạn! Điều này làm cho nó hoạt động! – Slim

9

Đây là ví dụ hoạt động sử dụng bảng điều khiển để viết một ô đơn lẻ. Cảm ơn tất cả những người đã hỗ trợ !!

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

     } 
    } 
} 
+0

hoạt động tốt, nhưng nó được dịch như thế nào để trở thành một phần của BatchUpdate? tức là, nếu tôi muốn cập nhật 2 phạm vi (có tên) trong một yêu cầu, tôi sẽ làm như thế nào? – mcmillab

+0

Xin chào @Slim, Giải pháp này đã giúp tôi nhưng tôi muốn bất kỳ giải pháp nào tạo tệp trên googleDrive Bạn có thể vui lòng giúp tôi! –

Các vấn đề liên quan