【问题标题】:How do I take a users input and update a Google spreadsheet in c#如何在 C# 中获取用户输入并更新 Google 电子表格
【发布时间】:2020-02-25 18:47:56
【问题描述】:

我有一个 Google 电子表格,用作文具室的库存清单。这在 c# 中被证明是一个具有挑战性的构建,因为我需要让用户输入他们想要多少支笔并更新电子表格中的 qty 字段。我可以通过硬编码来做到这一点,但是如何更改它以获取用户输入。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using System;
using System.Collections.Generic;
using System.IO;

//Database https://docs.google.com/spreadsheets/d/HIDDEN/edit?ts=5e53e5e8#gid=0
/*

STOCK LIST
Col A = Item
Col B = Item Code
Col C = Qty
Col D = Unit Price
Col E = Date Added
Col F = Stock updated(After delivery)
COL G = Total Cost
Col H = Total Expenditure

USERS
Last Name   First Name  UserName    PassWord
Knight      Fiona       FK1         Cat
Wilson      Euan        EW1         StarWars
Mansfield   Graham      GM1         Snarler
Account     Test        TA1         Test
*/


namespace StockList
{
   class Program
   {
       //Read The Sheet
       static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
       static readonly string ApplicationName = "Stock List";
       static readonly string SpreadsheetId = "HIDDEN";
       static readonly string sheet = "Stock";
       static readonly string sheet1 = "Employees";
       static SheetsService service;
       //Update the database
       static void Main(string[] args)
       {
           GoogleCredential credential;
           using (var stream = new FileStream("Stock.json", FileMode.Open, FileAccess.Read))
           {
               credential = GoogleCredential.FromStream(stream)
                   .CreateScoped(Scopes);
           }
           // Create Google Sheets API service.
           service = new SheetsService(new BaseClientService.Initializer()
           {
               HttpClientInitializer = credential,
               ApplicationName = ApplicationName,
           });

           Console.WriteLine("Welcome to the Stationery Management Service!");

           //Console.WriteLine("Please enter your Username");
           //var userName = Console.ReadLine();


           Console.WriteLine("\nCurrent Stock Level: \n");
           ReadEntriesStock();
           UpdateEntry();
           Console.WriteLine("\nNew Stock:\n");
           ReadEntriesStock();
           Console.WriteLine("\nEmployees List:\n");
           ReadEntriesEmployees();
           Console.WriteLine("\n");
           UpdateEntryEmployee();

       }
       static void ReadEntriesStock()
       {
           var range = $"{sheet}!A:F";
           SpreadsheetsResource.ValuesResource.GetRequest request =
                   service.Spreadsheets.Values.Get(SpreadsheetId, range);
           var response = request.Execute();
           IList<IList<object>> values = response.Values;
           if (values != null && values.Count > 0)
           {
               Console.ForegroundColor = ConsoleColor.Yellow;
               Console.WriteLine("  {0,8} {1} {2,5} {3,2} {4,2} {5} {6,6} {1,2} {8,7}", "Item", "|", "Stock Code", "|", "Quantity", "|", "Price", "|", "Date");
               Console.WriteLine("   --------------------------------------------------------");
               Console.ResetColor();
               foreach (var row in values)
               {
                   // Print columns A to E, which correspond to indices 0 and 4.

                   Console.WriteLine("{0,10} |{1,8}     | {2,5}    |{3,7}  | {4,5}", row[0], row[1],  row[2], row[3], row[4]);
               }
           }
           else
           {
               Console.WriteLine("No data found.");
           }
       }
       static void ReadEntriesEmployees()
       {
           var range = $"{sheet1}!A:B";
           SpreadsheetsResource.ValuesResource.GetRequest request =
                   service.Spreadsheets.Values.Get(SpreadsheetId, range);
           var response = request.Execute();
           IList<IList<object>> values = response.Values;
           if (values != null && values.Count > 0)
           {
               foreach (var row in values)
               {
                   // Print columns A to E, which correspond to indices 0 and 4.
                   Console.WriteLine("{0,5} | {1,5}", row[0], row[1]);
               }
           }
           else
           {
               Console.WriteLine("No data found.");
           }
       }
       static void UpdateEntry()
       {
           var range = $"{sheet}!C1";
           var valueRange = new ValueRange();
           var oblist = new List<object>() { "87" };
           valueRange.Values = new List<IList<object>> { oblist };
           var updateRequest = service.Spreadsheets.Values.Update(valueRange, SpreadsheetId, range);
           updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
           var appendReponse = updateRequest.Execute();
       }
       static void UpdateEntryEmployee()
       {
           var range = $"{sheet1}!C6";
           var valueRange = new ValueRange();
           var oblist = new List<object>() { "" };
           valueRange.Values = new List<IList<object>> { oblist };
           var updateRequest = service.Spreadsheets.Values.Update(valueRange, SpreadsheetId, range);
           updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
           var appendReponse = updateRequest.Execute();
       }
   }
}

【问题讨论】:

  • 提示用户,然后Console.ReadLine()。测试用户输入是否有效,然后将其与电子表格中的相应单元格相加。

标签: c# google-sheets-api


【解决方案1】:

我创建了一个可重用的函数,它接受一个以竖线分隔的字符串并将其逐行写入指定的工作表中。我在 DLL 中执行此操作,因此我通常避免从控制台读取/写入。

private string GoogleSheetsUpdate(string fileId, string inputOption, string inputRange, string inputText) {
        //PURPOSE: SETS VALUES IN A RANGE OF A SPREADSHEET.
        //REFERENCE: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update
        string result = "Success";
        try {
            //HOW THE INPUT DATA SHOULD BE INTERPRETED:
            //THE VALUES WILL BE PARSED AS IF THE USER TYPED THEM INTO THE UI. NUMBERS WILL STAY AS NUMBERS, BUT STRINGS MAY BE CONVERTED
            //TO NUMBERS, DATES, ETC.FOLLOWING THE SAME RULES THAT ARE APPLIED WHEN ENTERING TEXT INTO A CELL VIA THE GOOGLE SHEETS UI.
            SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum valueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
            inputOption = inputOption.ToLower();
            if (inputOption == "raw") {
                //THE VALUES THE USER HAS ENTERED WILL NOT BE PARSED AND WILL BE STORED AS-IS.
                valueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
            }

            //ASSIGN VALUES TO DESIRED PROPERTIES OF REQUESTBODY; ALL EXISTING PROPERTIES WILL BE REPLACED
            string[] oRow = inputText.Split('|');
            ValueRange oBody = new ValueRange {
                Values = new List<IList<object>> { oRow },
            };
            SpreadsheetsResource.ValuesResource.UpdateRequest oRequest = sheetsService.Spreadsheets.Values.Update(oBody, fileId, inputRange);
            oRequest.ValueInputOption = valueInputOption;
            UpdateValuesResponse oResponse = oRequest.Execute();
        } catch (Exception e) {
            result = "Google Sheets API: " + e.Message;
        }
        return result;
        //RESPONSE: IF SUCCESSFUL, THE RESPONSE BODY CONTAINS AN INSTANCE OF UPDATEVALUESRESPONSE.
    }

【讨论】:

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