【问题标题】:Find the sheet with SpreadSheetId and SheetId C#使用 SpreadSheetId 和 SheetId C# 查找工作表
【发布时间】:2020-08-24 10:31:47
【问题描述】:

我目前正在使用正则表达式在 url 中查找 google sheet 的“SpreadSheetId”和“SheetId”。我可以找到带有“SpreadSheetId”和工作表名称的文件,但是...... 我不明白为什么我不能使用“SheetId”来找到它。它仅适用于工作表的确切名称。

Google API V4:https://developers.google.com/sheets/api/quickstart/dotnet

如何找到带有 sheetId 而不是名称的工作表。

            UserCredential credential;

            using (var stream =
                new FileStream("code_secret_client.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,
            });

        // Define request parameters.
        //1HtsjLDHo9oaNqeSPKt8YRCEKg5lfa9ONzytJm_6thS4
        //find regex
        Regex RxSpreadSheetId = new Regex(@"/spreadsheets/d/([a-zA-Z0-9-_]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        Regex RxSheetId = new Regex(@"[#&]gid=([0-9]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        // 
        string URL = string.Copy(textBox2.Text);
        Match MatchSpreadSheetId = RxSpreadSheetId.Match(URL);
        Match MatchSheetId = RxSheetId.Match(URL);
        String SpreadSheetId = MatchSpreadSheetId.Groups[1].Value;
        String SheetId = MatchSheetId.Groups[1].Value;
        String range = SheetId + "!A2:B";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(SpreadSheetId, range);

            // Prints the names and majors of students in a sample spreadsheet:
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
            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 and 4.
                Console.WriteLine("{0}, {1}", row[0], row[1]);
                richTextBox1.Text = (string)row[1];
                }
            }
            else
            {
                Console.WriteLine("No data found.");
            }
            Console.Read();
        
    }

【问题讨论】:

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


    【解决方案1】:

    google-sheets-api 要求范围名称是字符串,因此工作表的整数 id 将不起作用。一种解决方法是使用 api 将 id 转换为工作表名称。这可以在 C# 中完成,如下所示:

    private static string GetSheetNameByID(string SpreadSheetID, int SheetID, SheetsService Service)
    {
        //we just want the sheet name so don't retrieve any data
        List<string> ranges = new List<string>();
        bool includeGridData = false;
    
        SpreadsheetsResource.GetRequest request = Service.Spreadsheets.Get(SpreadSheetID);
        request.Ranges = ranges;
        request.IncludeGridData = includeGridData;
    
        // To execute asynchronously in an async method, replace `request.Execute()` as shown:
        Data.Spreadsheet response = request.Execute();
    
        foreach(var sheet in response.Sheets)
        {
            if (sheet.Properties.SheetId == SheetID)
            {
                return sheet.Properties.Title;
            }
        }
    
        return null;
    }
    

    从您的代码中您可以调用:

    var name = GetSheetNameByID(SpreadSheetId, SheetId, service);

    【讨论】:

    • 感谢您的回答!但是 SheetsService 参数是什么?
    • 从您的代码中,您将传递 var service 变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    相关资源
    最近更新 更多