在C#中使用googlesheets API v4获取命名范围的列表

时间:2019-10-13 10:27:55

标签: google-sheets-api

我需要能够在电子表格中获得所有命名范围的列表,但无法弄清楚该怎么做。

我找到了以下代码,但没有找到c#-如何在c#中执行相同的操作?

Code that does what I need but not in c#

function getNamedRanges2(spreadsheetId) {
    var ss = SpreadsheetApp.openById(spreadsheetId);
    var sheetIdToName = {};
    ss.getSheets().forEach(function(e) {
        sheetIdToName[e.getSheetId()] = e.getSheetName();
    });
    var result = {};
    Sheets.Spreadsheets.get(spreadsheetId, {fields: "namedRanges"})
        .namedRanges.forEach(function(e) {
            var sheetName = sheetIdToName[e.range.sheetId.toString()];
            var a1notation = ss.getSheetByName(sheetName).getRange(
                e.range.startRowIndex + 1,
                e.range.startColumnIndex + 1,
                e.range.endRowIndex - e.range.startRowIndex,
                e.range.endColumnIndex - e.range.startColumnIndex
            ).getA1Notation();
            result[e.name] = sheetName + "!" + a1notation;
        });
    return result;
}

function main() {
    var spreadsheetId = "### spreadsheet ID ###";
    var result = getNamedRanges2(spreadsheetId);
    Logger.log(JSON.stringify(result));
}

1 个答案:

答案 0 :(得分:0)

基于Quickstart for Sheets APIMethod: spreadsheets.get 2的C#示例代码,可以将以下两个代码段组合在一起,以检索命名范围:

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.Threading;
using Newtonsoft.Json;
using Data = Google.Apis.Sheets.v4.Data;

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

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.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,
            });
            // The spreadsheet to request.
            string spreadsheetId = "YOUR SPREADSHEET ID";  
            // TODO: Update placeholder value.

            SpreadsheetsResource.GetRequest request = service.Spreadsheets.Get(spreadsheetId);
            request.Fields = "namedRanges";
            // To execute asynchronously in an async method, replace `request.Execute()` as shown:
            Data.Spreadsheet response = request.Execute();

            // TODO: Change code below to process the `response` object:
            Console.WriteLine(JsonConvert.SerializeObject(response));
         }
    }
}

指定request.Fields = "namedRanges";时,响应将仅包含命名范围。