C#Google API(SheetsServices)插入新行

时间:2016-08-24 07:06:30

标签: c# google-api

我如何在谷歌电子表格中插入新行。

使用Google API(SheetsServices)。

class GoogleAPI
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        static string[] Scopes = { SheetsService.Scope.Spreadsheets, "email" };
        static string ApplicationName = "Google Sheets API .NET Quickstart";

        public GoogleAPI()
        {
            UserCredential credential;

            using (var stream =
                new FileStream("Secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/Secret.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 Plus API service.
            var plusService = new PlusService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

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

            var me = plusService.People.Get("me").Execute();
            var useremail = me.Emails.FirstOrDefault().Value;
        }
    }

到目前为止,我已经能够

  • 使用OAuth2
  • 对用户进行身份验证
  • 获取允许访问的电子邮件

问题:如何在工作表中插入新行。

其他问题:是否可以将LINQ绑定到我的电子表格?

1 个答案:

答案 0 :(得分:5)

在等待某人回答后尝试了一下,我突然意识到答案。所以我会在这里为其他人发布。

            IList<Object> obj = new List<Object>();
            obj.Add("A2");
            obj.Add("B2");
            IList<IList<Object>> values = new List<IList<Object>>();
            values.Add(obj);

            SpreadsheetsResource.ValuesResource.AppendRequest request =
                    service.Spreadsheets.Values.Append(new ValueRange() { Values = values }, spreadsheetId, range);
            request.InsertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
            request.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.RAW;
            var response = request.Execute();

.InsertDataOption允许将其添加为新行。

.ValueInputOption是必需的,起初我没有设置它并且出错。