skip to Main Content

I have a console C# app and i use Google Sheets API to get data from spreadsheet. API returns me the following:

{"majorDimension":"ROWS","range":"Sheet1!A2:H1000","values":[["Test1","20/07/2023","21/07/2023"],["Test2","10/08/2023","12/08/2023"]],"ETag":null}

These "values" are actually the values from the cells, and I need to loop through those values to extract the values "Test" and "Test2". Does anyone know how to do this?

var sheetRequest = sheetService.Spreadsheets.Values.Get(spreadsheetId, "A2:H");

        var sheetResponse = await sheetRequest.ExecuteAsync();

        for (int i = 0; i < sheetResponse.Values.Count; i++)
        {
            for (int j = 0; j < sheetResponse.Values.Count; j++)
            {
                string s = (string)sheetResponse.Values[i][j];
                Console.WriteLine(s);
            }
        

I tried this. I don’t know how to access elements? What is wrong?

2

Answers


  1. As @orhtej2 has pointed out, you are missing a [i]. The code should be

    for (int i = 0; i < sheetResponse.values.Count; i++)
    {
        for (int j = 0; j < sheetResponse.values[i].Count; j++)
        {
            Console.WriteLine(sheetResponse.values[i][j]);
        }
    }
    

    I am voting to close this as a typo.

    Login or Signup to reply.
  2. please try this.

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    
    // Your JSON string
    string jsonString = " 
    {"majorDimension":"ROWS","range":"Sheet1!A2:H1000","values":[["Test1","20/07/2023","21/07/2023"],["Test2","10/08/2023","12/08/2023"]],"ETag":null}";
    
    // Parse the JSON string into a JObject
    JObject jsonObject = JObject.Parse(jsonString);
    
    // Access the "values" array
    JArray valuesArray = (JArray)jsonObject["values"];
    
    // Iterate over the "values" array
    foreach (JArray innerArray in valuesArray)
    {
        foreach (JToken token in innerArray)
        {
            Console.WriteLine(token.ToString());
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search