如何在C#中使用API​​ v4创建新的Google表格

时间:2017-10-13 17:52:32

标签: c# .net google-sheets-api

我一直在研究Google表格API和Google指南,但我似乎找不到任何示例来创建新的Google表格(工作簿)。我可以从一张纸上阅读,但要弄清楚如何创建一个新的。

以下是我从Google表格中读取的代码:

    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 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String range = "Class Data!A2:E";
        SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);

        ValueRange response = request.Execute();
        IList<IList<Object>> values = response.Values;
        if (values != null && values.Count > 0)
        {
            Console.WriteLine("Name, Major");
            foreach (var row in values)
            {
                // Print columns A and E, which correspond to indices 0 - 4
                Console.WriteLine("{0}, {1}", row[0], row[4]);
            }
        }
        else
        {
            Console.WriteLine("No data found.");
        }
        Console.Read();

    }

1 个答案:

答案 0 :(得分:1)

对于Sheetsv4,我建议使用Method.spreadsheets.create,因为它的会创建一个电子表格,并返回新创建的电子表格。您可以在Sheetsv4 reference

中检查Sheets APIv4支持的所有方法