【问题标题】:How to add a sheet in google sheets API v4 in C#?如何在 C# 中的 google sheet API v4 中添加工作表?
【发布时间】:2016-06-03 20:50:44
【问题描述】:

我一直在使用 Google Sheets API,并关注 The Google Guide。但是,即使在 google 的第二页之外,也没有任何示例可以添加工作表并写入 .NET 中的新工作表。 js 有很多,但我不知道如何 1)添加工作表或 2)写入新工作表。

我该怎么做?现在我可以毫无问题地阅读示例中的内容,而且我只找到了 one 其他对 v4 C# 的引用。我尝试回到 v3,但所有文档都强烈建议使用 v4。

有人能做到吗?到目前为止,这是我能做的所有事情:

        // Create Google Sheets API service.
        var service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define request parameters.
        // Add new Sheet
        string sheetName = string.Format("{0} {1}", DateTime.Now.Month, DateTime.Now.Day);
        AddSheetRequest addSheetRequest = new AddSheetRequest();
        addSheetRequest.Properties.Title = sheetName;

        // How do I tell this to update??

【问题讨论】:

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


    【解决方案1】:

    为了将来拯救某人的头痛以结束所有头痛。经过数小时的反复试验,我想出了如何添加工作表。 仍在研究如何更新值。

    我是这样做的:

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
    
            // Add new Sheet
            string sheetName = string.Format("{0} {1}", DateTime.Now.Month, DateTime.Now.Day);
            var addSheetRequest = new AddSheetRequest();
            addSheetRequest.Properties = new SheetProperties();
            addSheetRequest.Properties.Title = sheetName;
            BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
            batchUpdateSpreadsheetRequest.Requests = new List<Request>();
            batchUpdateSpreadsheetRequest.Requests.Add(new Request
            {
                AddSheet = addSheetRequest
            });
    
            var batchUpdateRequest =
                service.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, spreadsheetId);
    
            batchUpdateRequest.Execute();
    

    【讨论】:

    • 非常有帮助!但我有一个问题:既然我们正在创建一个新的电子表格,我们还没有电子表格 ID,对吗?那么你从哪里得到这个值呢?
    • @JeffreyBlake “电子表格”指的是现有“工作表”中的选项卡。这里的spreadsheetId 指的是这个工作表的ID,一般可以在URL(docs.google.com/spreadsheets/d/<spreadsheetId>)中找到。希望这会有所帮助。
    • @JeffreyBlake - 第一次创建电子表格时,Google 会为您分配 ID。创建SheetService 对象后,您创建一个新的Spreadsheet 对象,其中填写了Properties,但没有填写电子表格ID。当您调用 service.Spreadsheets.Create(yourspvar).Execute() 时,返回值包括分配的 ID。
    【解决方案2】:

    我一直在寻找这个的 Java 版本,并且我设法根据 sparky 的答案获得了一个工作版本。这应该有效:

                //Set sheet name
                //Can be any string, I chose to set it to the account name
                String sheetName = mCredential.getSelectedAccountName();
    
                //Create a new AddSheetRequest
                AddSheetRequest addSheetRequest = new AddSheetRequest();
                SheetProperties sheetProperties = new SheetProperties();
    
                //Add the sheetName to the sheetProperties
                addSheetRequest.setProperties(sheetProperties);
                addSheetRequest.setProperties(sheetProperties.setTitle(sheetName));
    
                //Create batchUpdateSpreadsheetRequest
                BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
    
                //Create requestList and set it on the batchUpdateSpreadsheetRequest
                List<Request> requestsList = new ArrayList<Request>();
                batchUpdateSpreadsheetRequest.setRequests(requestsList);
    
                //Create a new request with containing the addSheetRequest and add it to the requestList
                Request request = new Request();
                request.setAddSheet(addSheetRequest);
                requestsList.add(request);
    
                //Add the requestList to the batchUpdateSpreadsheetRequest
                batchUpdateSpreadsheetRequest.setRequests(requestsList);
    
                //Call the sheets API to execute the batchUpdate
                mService.spreadsheets().batchUpdate(spreadsheetId,batchUpdateSpreadsheetRequest).execute();
    

    【讨论】:

      【解决方案3】:

      我也有添加工作表的代码,但您似乎想通了。这是一些将内容添加到工作表的代码。它与其他人发布的内容略有不同,但它应该对看到这篇文章的人有所帮助。

      在此代码中,它将 colNames 的值插入从 (0,0) 开始的行中。因此,如果 sheet 使用此表示法(行、列),则
      (0,0)=时间戳
      (0,1)=videoid
      (0,2)=视频名称
      (0,3)=名字
      (0,4)=姓氏
      (0,5)=电子邮件

      所以整个第一行将被 colNames 值填充

              var reqs = new BatchUpdateSpreadsheetRequest();
              reqs.Requests = new List<Request>();
              string[] colNames = new [] { "timestamp", "videoid", "videoname", "firstname", "lastname", "email" };
      
              // Create starting coordinate where data would be written to
      
              GridCoordinate gc = new GridCoordinate();
              gc.ColumnIndex = 0;
              gc.RowIndex = 0;
              gc.SheetId = SHEETID; // Your specific sheet ID here
      
              rq = new Request();
              rq.UpdateCells = new UpdateCellsRequest();
              rq.UpdateCells.Start = gc;
              rq.UpdateCells.Fields = "*"; // needed by API, throws error if null
      
              // Assigning data to cells
              RowData rd = new RowData();
              List<CellData> lcd = new List<CellData>();
              foreach (String column in colNames)
              {
                  ExtendedValue ev = new ExtendedValue();
                  ev.StringValue = column;
      
                  CellData cd = new CellData();
                  cd.UserEnteredValue = ev;
                  lcd.Add(cd);
              }
              rd.Values = lcd;
      
              // Put cell data into a row
              List<RowData> lrd = new List<RowData>();
              lrd.Add(rd);
              rq.UpdateCells.Rows = lrd;
      
              // It's a batch request so you can create more than one request and send them all in one batch. Just use reqs.Requests.Add() to add additional requests for the same spreadsheet
              reqs.Requests.Add(rq);
      
              // Execute request
              response = sheetsService.Spreadsheets.BatchUpdate(reqs, Spreadsheet.SpreadsheetId).Execute(); // Replace Spreadsheet.SpreadsheetId with your recently created spreadsheet ID
      

      【讨论】:

        【解决方案4】:

        仅供参考,虽然大部分文档只是使用原始 JSON,但它应该 1:1 映射到每种语言的结构。

        例如,要更新值,您可能会执行以下操作:

        var valueRange = new ValueRange(); valueRange.values = { { 1, 2, 3 }, { 4, 5, 6 } }; var range = "A1"; var update = service.Spreadsheets.Values.Update(valueRange, spreadsheetId, range); var result = update.execute();

        以上是基于您的代码示例和参考文档@https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update 的伪代码。

        【讨论】:

          【解决方案5】:

          进一步扩展 Sam 的答案。以下让我更新一个单元格。

                      ValueRange VRx = new ValueRange();
                      IList<IList<object>> xx = new List<IList<object>>();
                      xx.Add(new List<object> { "test" });
                      VRx.Values = xx;
                      SpreadsheetsResource.ValuesResource.UpdateRequest update = service.Spreadsheets.Values.Update(VRx, spreadsheetId, "back!A19");
                      update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
                      UpdateValuesResponse result = update.Execute(); 
          

          希望这会有所帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多